1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2024, 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 Debug
; use Debug
;
28 with Einfo
; use Einfo
;
29 with Einfo
.Entities
; use Einfo
.Entities
;
30 with Einfo
.Utils
; use Einfo
.Utils
;
31 with Elists
; use Elists
;
32 with Eval_Fat
; use Eval_Fat
;
33 with Exp_Ch11
; use Exp_Ch11
;
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_Cat
; use Sem_Cat
;
52 with Sem_Disp
; use Sem_Disp
;
53 with Sem_Elab
; use Sem_Elab
;
54 with Sem_Eval
; use Sem_Eval
;
55 with Sem_Mech
; use Sem_Mech
;
56 with Sem_Res
; use Sem_Res
;
57 with Sem_Util
; use Sem_Util
;
58 with Sem_Warn
; use Sem_Warn
;
59 with Sinfo
; use Sinfo
;
60 with Sinfo
.Nodes
; use Sinfo
.Nodes
;
61 with Sinfo
.Utils
; use Sinfo
.Utils
;
62 with Sinput
; use Sinput
;
63 with Snames
; use Snames
;
64 with Sprint
; use Sprint
;
65 with Stand
; use Stand
;
66 with Stringt
; use Stringt
;
67 with Targparm
; use Targparm
;
68 with Tbuild
; use Tbuild
;
69 with Ttypes
; use Ttypes
;
70 with Validsw
; use Validsw
;
72 package body Checks
is
74 -- General note: many of these routines are concerned with generating
75 -- checking code to make sure that constraint error is raised at runtime.
76 -- Clearly this code is only needed if the expander is active, since
77 -- otherwise we will not be generating code or going into the runtime
80 -- We therefore disconnect most of these checks if the expander is
81 -- inactive. This has the additional benefit that we do not need to
82 -- worry about the tree being messed up by previous errors (since errors
83 -- turn off expansion anyway).
85 -- There are a few exceptions to the above rule. For instance routines
86 -- such as Apply_Scalar_Range_Check that do not insert any code can be
87 -- safely called even when the Expander is inactive (but Errors_Detected
88 -- is 0). The benefit of executing this code when expansion is off, is
89 -- the ability to emit constraint error warnings for static expressions
90 -- even when we are not generating code.
92 -- The above is modified in gnatprove mode to ensure that proper check
93 -- flags are always placed, even if expansion is off.
95 -------------------------------------
96 -- Suppression of Redundant Checks --
97 -------------------------------------
99 -- This unit implements a limited circuit for removal of redundant
100 -- checks. The processing is based on a tracing of simple sequential
101 -- flow. For any sequence of statements, we save expressions that are
102 -- marked to be checked, and then if the same expression appears later
103 -- with the same check, then under certain circumstances, the second
104 -- check can be suppressed.
106 -- Basically, we can suppress the check if we know for certain that
107 -- the previous expression has been elaborated (together with its
108 -- check), and we know that the exception frame is the same, and that
109 -- nothing has happened to change the result of the exception.
111 -- Let us examine each of these three conditions in turn to describe
112 -- how we ensure that this condition is met.
114 -- First, we need to know for certain that the previous expression has
115 -- been executed. This is done principally by the mechanism of calling
116 -- Conditional_Statements_Begin at the start of any statement sequence
117 -- and Conditional_Statements_End at the end. The End call causes all
118 -- checks remembered since the Begin call to be discarded. This does
119 -- miss a few cases, notably the case of a nested BEGIN-END block with
120 -- no exception handlers. But the important thing is to be conservative.
121 -- The other protection is that all checks are discarded if a label
122 -- is encountered, since then the assumption of sequential execution
123 -- is violated, and we don't know enough about the flow.
125 -- Second, we need to know that the exception frame is the same. We
126 -- do this by killing all remembered checks when we enter a new frame.
127 -- Again, that's over-conservative, but generally the cases we can help
128 -- with are pretty local anyway (like the body of a loop for example).
130 -- Third, we must be sure to forget any checks which are no longer valid.
131 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
132 -- used to note any changes to local variables. We only attempt to deal
133 -- with checks involving local variables, so we do not need to worry
134 -- about global variables. Second, a call to any non-global procedure
135 -- causes us to abandon all stored checks, since such a all may affect
136 -- the values of any local variables.
138 -- The following define the data structures used to deal with remembering
139 -- checks so that redundant checks can be eliminated as described above.
141 -- Right now, the only expressions that we deal with are of the form of
142 -- simple local objects (either declared locally, or IN parameters) or
143 -- such objects plus/minus a compile time known constant. We can do
144 -- more later on if it seems worthwhile, but this catches many simple
145 -- cases in practice.
147 -- The following record type reflects a single saved check. An entry
148 -- is made in the stack of saved checks if and only if the expression
149 -- has been elaborated with the indicated checks.
151 type Saved_Check
is record
153 -- Set True if entry is killed by Kill_Checks
156 -- The entity involved in the expression that is checked
159 -- A compile time value indicating the result of adding or
160 -- subtracting a compile time value. This value is to be
161 -- added to the value of the Entity. A value of zero is
162 -- used for the case of a simple entity reference.
164 Check_Type
: Character;
165 -- This is set to 'R' for a range check (in which case Target_Type
166 -- is set to the target type for the range check) or to 'O' for an
167 -- overflow check (in which case Target_Type is set to Empty).
169 Target_Type
: Entity_Id
;
170 -- Used only if Do_Range_Check is set. Records the target type for
171 -- the check. We need this, because a check is a duplicate only if
172 -- it has the same target type (or more accurately one with a
173 -- range that is smaller or equal to the stored target type of a
177 -- The following table keeps track of saved checks. Rather than use an
178 -- extensible table, we just use a table of fixed size, and we discard
179 -- any saved checks that do not fit. That's very unlikely to happen and
180 -- this is only an optimization in any case.
182 Saved_Checks
: array (Int
range 1 .. 200) of Saved_Check
;
183 -- Array of saved checks
185 Num_Saved_Checks
: Nat
:= 0;
186 -- Number of saved checks
188 -- The following stack keeps track of statement ranges. It is treated
189 -- as a stack. When Conditional_Statements_Begin is called, an entry
190 -- is pushed onto this stack containing the value of Num_Saved_Checks
191 -- at the time of the call. Then when Conditional_Statements_End is
192 -- called, this value is popped off and used to reset Num_Saved_Checks.
194 -- Note: again, this is a fixed length stack with a size that should
195 -- always be fine. If the value of the stack pointer goes above the
196 -- limit, then we just forget all saved checks.
198 Saved_Checks_Stack
: array (Int
range 1 .. 100) of Nat
;
199 Saved_Checks_TOS
: Nat
:= 0;
201 -----------------------
202 -- Local Subprograms --
203 -----------------------
205 procedure Apply_Arithmetic_Overflow_Strict
(N
: Node_Id
);
206 -- Used to apply arithmetic overflow checks for all cases except operators
207 -- on signed arithmetic types in MINIMIZED/ELIMINATED case (for which we
208 -- call Apply_Arithmetic_Overflow_Minimized_Eliminated below). N can be a
209 -- signed integer arithmetic operator (but not an if or case expression).
210 -- It is also called for types other than signed integers.
212 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated
(Op
: Node_Id
);
213 -- Used to apply arithmetic overflow checks for the case where the overflow
214 -- checking mode is MINIMIZED or ELIMINATED and we have a signed integer
215 -- arithmetic op (which includes the case of if and case expressions). Note
216 -- that Do_Overflow_Check may or may not be set for node Op. In these modes
217 -- we have work to do even if overflow checking is suppressed.
219 procedure Apply_Division_Check
224 -- N is an N_Op_Div, N_Op_Rem, or N_Op_Mod node. This routine applies
225 -- division checks as required if the Do_Division_Check flag is set.
226 -- Rlo and Rhi give the possible range of the right operand, these values
227 -- can be referenced and trusted only if ROK is set True.
229 procedure Apply_Float_Conversion_Check
231 Target_Typ
: Entity_Id
);
232 -- The checks on a conversion from a floating-point type to an integer
233 -- type are delicate. They have to be performed before conversion, they
234 -- have to raise an exception when the operand is a NaN, and rounding must
235 -- be taken into account to determine the safe bounds of the operand.
237 procedure Apply_Selected_Length_Checks
239 Target_Typ
: Entity_Id
;
240 Source_Typ
: Entity_Id
;
241 Do_Static
: Boolean);
242 -- This is the subprogram that does all the work for Apply_Length_Check
243 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
244 -- described for the above routines. The Do_Static flag indicates that
245 -- only a static check is to be done.
247 procedure Compute_Range_For_Arithmetic_Op
256 -- Given an integer arithmetical operation Op and the range of values of
257 -- its operand(s), try to compute a conservative estimate of the possible
258 -- range of values for the result of the operation. Thus if OK is True on
259 -- return, the result is known to lie in the range Lo .. Hi (inclusive).
260 -- If OK is false, both Lo and Hi are set to No_Uint.
262 type Check_Type
is new Check_Id
range Access_Check
.. Division_Check
;
263 function Check_Needed
(Nod
: Node_Id
; Check
: Check_Type
) return Boolean;
264 -- This function is used to see if an access or division by zero check is
265 -- needed. The check is to be applied to a single variable appearing in the
266 -- source, and N is the node for the reference. If N is not of this form,
267 -- True is returned with no further processing. If N is of the right form,
268 -- then further processing determines if the given Check is needed.
270 -- The particular circuit is to see if we have the case of a check that is
271 -- not needed because it appears in the right operand of a short circuited
272 -- conditional where the left operand guards the check. For example:
274 -- if Var = 0 or else Q / Var > 12 then
278 -- In this example, the division check is not required. At the same time
279 -- we can issue warnings for suspicious use of non-short-circuited forms,
282 -- if Var = 0 or Q / Var > 12 then
288 Check_Type
: Character;
289 Target_Type
: Entity_Id
;
290 Entry_OK
: out Boolean;
294 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
295 -- to see if a check is of the form for optimization, and if so, to see
296 -- if it has already been performed. Expr is the expression to check,
297 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
298 -- Target_Type is the target type for a range check, and Empty for an
299 -- overflow check. If the entry is not of the form for optimization,
300 -- then Entry_OK is set to False, and the remaining out parameters
301 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
302 -- entity and offset from the expression. Check_Num is the number of
303 -- a matching saved entry in Saved_Checks, or zero if no such entry
306 function Get_Discriminal
(E
: Entity_Id
; Bound
: Node_Id
) return Node_Id
;
307 -- If a discriminal is used in constraining a prival, Return reference
308 -- to the discriminal of the protected body (which renames the parameter
309 -- of the enclosing protected operation). This clumsy transformation is
310 -- needed because privals are created too late and their actual subtypes
311 -- are not available when analysing the bodies of the protected operations.
312 -- This function is called whenever the bound is an entity and the scope
313 -- indicates a protected operation. If the bound is an in-parameter of
314 -- a protected operation that is not a prival, the function returns the
316 -- To be cleaned up???
318 function Guard_Access
321 Expr
: Node_Id
) return Node_Id
;
322 -- In the access type case, guard the test with a test to ensure
323 -- that the access value is non-null, since the checks do not
324 -- not apply to null access values.
326 procedure Install_Static_Check
327 (R_Cno
: Node_Id
; Loc
: Source_Ptr
; Reason
: RT_Exception_Code
);
328 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
329 -- Constraint_Error node.
331 function Is_Signed_Integer_Arithmetic_Op
(N
: Node_Id
) return Boolean;
332 -- Returns True if node N is for an arithmetic operation with signed
333 -- integer operands. This includes unary and binary operators, and also
334 -- if and case expression nodes where the dependent expressions are of
335 -- a signed integer type. These are the kinds of nodes for which special
336 -- handling applies in MINIMIZED or ELIMINATED overflow checking mode.
338 function Range_Or_Validity_Checks_Suppressed
339 (Expr
: Node_Id
) return Boolean;
340 -- Returns True if either range or validity checks or both are suppressed
341 -- for the type of the given expression, or, if the expression is the name
342 -- of an entity, if these checks are suppressed for the entity.
344 function Selected_Length_Checks
346 Target_Typ
: Entity_Id
;
347 Source_Typ
: Entity_Id
;
348 Warn_Node
: Node_Id
) return Check_Result
;
349 -- Like Apply_Selected_Length_Checks, except it doesn't modify
350 -- anything, just returns a list of nodes as described in the spec of
351 -- this package for the Get_Range_Checks function.
352 -- ??? In fact it does construct the test and insert it into the tree,
353 -- and insert actions in various ways (calling Insert_Action directly
354 -- in particular) so we do not call it in GNATprove mode, contrary to
355 -- Selected_Range_Checks.
357 function Selected_Range_Checks
359 Target_Typ
: Entity_Id
;
360 Source_Typ
: Entity_Id
;
361 Warn_Node
: Node_Id
) return Check_Result
;
362 -- Like Apply_Range_Check, except it does not modify anything, just
363 -- returns a list of nodes as described in the spec of this package
364 -- for the Get_Range_Checks function.
366 ------------------------------
367 -- Access_Checks_Suppressed --
368 ------------------------------
370 function Access_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
372 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
373 return Is_Check_Suppressed
(E
, Access_Check
);
375 return Scope_Suppress
.Suppress
(Access_Check
);
377 end Access_Checks_Suppressed
;
379 -------------------------------------
380 -- Accessibility_Checks_Suppressed --
381 -------------------------------------
383 function Accessibility_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
385 if No_Dynamic_Accessibility_Checks_Enabled
(E
) then
388 elsif Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
389 return Is_Check_Suppressed
(E
, Accessibility_Check
);
392 return Scope_Suppress
.Suppress
(Accessibility_Check
);
394 end Accessibility_Checks_Suppressed
;
396 -----------------------------
397 -- Activate_Division_Check --
398 -----------------------------
400 procedure Activate_Division_Check
(N
: Node_Id
) is
402 Set_Do_Division_Check
(N
, True);
403 Possible_Local_Raise
(N
, Standard_Constraint_Error
);
404 end Activate_Division_Check
;
406 -----------------------------
407 -- Activate_Overflow_Check --
408 -----------------------------
410 procedure Activate_Overflow_Check
(N
: Node_Id
) is
411 Typ
: constant Entity_Id
:= Etype
(N
);
414 -- Floating-point case. If Etype is not set (this can happen when we
415 -- activate a check on a node that has not yet been analyzed), then
416 -- we assume we do not have a floating-point type (as per our spec).
418 if Present
(Typ
) and then Is_Floating_Point_Type
(Typ
) then
420 -- Ignore call if we have no automatic overflow checks on the target
421 -- and Check_Float_Overflow mode is not set. These are the cases in
422 -- which we expect to generate infinities and NaN's with no check.
424 if not (Machine_Overflows_On_Target
or Check_Float_Overflow
) then
427 -- Ignore for unary operations ("+", "-", abs) since these can never
428 -- result in overflow for floating-point cases.
430 elsif Nkind
(N
) in N_Unary_Op
then
433 -- Otherwise we will set the flag
442 -- Nothing to do for Rem/Mod/Plus (overflow not possible, the check
443 -- for zero-divide is a divide check, not an overflow check).
445 if Nkind
(N
) in N_Op_Rem | N_Op_Mod | N_Op_Plus
then
450 -- Fall through for cases where we do set the flag
452 Set_Do_Overflow_Check
(N
);
453 Possible_Local_Raise
(N
, Standard_Constraint_Error
);
454 end Activate_Overflow_Check
;
456 --------------------------
457 -- Activate_Range_Check --
458 --------------------------
460 procedure Activate_Range_Check
(N
: Node_Id
) is
462 Set_Do_Range_Check
(N
);
463 Possible_Local_Raise
(N
, Standard_Constraint_Error
);
464 end Activate_Range_Check
;
466 ---------------------------------
467 -- Alignment_Checks_Suppressed --
468 ---------------------------------
470 function Alignment_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
472 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
473 return Is_Check_Suppressed
(E
, Alignment_Check
);
475 return Scope_Suppress
.Suppress
(Alignment_Check
);
477 end Alignment_Checks_Suppressed
;
479 ----------------------------------
480 -- Allocation_Checks_Suppressed --
481 ----------------------------------
483 -- Note: at the current time there are no calls to this function, because
484 -- the relevant check is in the run-time, so it is not a check that the
485 -- compiler can suppress anyway, but we still have to recognize the check
486 -- name Allocation_Check since it is part of the standard.
488 function Allocation_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
490 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
491 return Is_Check_Suppressed
(E
, Allocation_Check
);
493 return Scope_Suppress
.Suppress
(Allocation_Check
);
495 end Allocation_Checks_Suppressed
;
497 -------------------------
498 -- Append_Range_Checks --
499 -------------------------
501 procedure Append_Range_Checks
502 (Checks
: Check_Result
;
504 Suppress_Typ
: Entity_Id
;
505 Static_Sloc
: Source_Ptr
)
507 Checks_On
: constant Boolean :=
508 not Index_Checks_Suppressed
(Suppress_Typ
)
510 not Range_Checks_Suppressed
(Suppress_Typ
);
513 -- For now we just return if Checks_On is false, however this could be
514 -- enhanced to check for an always True value in the condition and to
515 -- generate a compilation warning.
517 if not Checks_On
then
522 exit when No
(Checks
(J
));
524 if Nkind
(Checks
(J
)) = N_Raise_Constraint_Error
525 and then Present
(Condition
(Checks
(J
)))
527 Append_To
(Stmts
, Checks
(J
));
531 Make_Raise_Constraint_Error
(Static_Sloc
,
532 Reason
=> CE_Range_Check_Failed
));
535 end Append_Range_Checks
;
537 ------------------------
538 -- Apply_Access_Check --
539 ------------------------
541 procedure Apply_Access_Check
(N
: Node_Id
) is
542 P
: constant Node_Id
:= Prefix
(N
);
545 -- We do not need checks if we are not generating code (i.e. the
546 -- expander is not active). This is not just an optimization, there
547 -- are cases (e.g. with pragma Debug) where generating the checks
548 -- can cause real trouble.
550 if not Expander_Active
then
554 -- No check if short circuiting makes check unnecessary
556 if not Check_Needed
(P
, Access_Check
) then
560 -- No check if accessing the Offset_To_Top component of a dispatch
561 -- table. They are safe by construction.
563 if Tagged_Type_Expansion
564 and then Present
(Etype
(P
))
565 and then Is_RTE
(Etype
(P
), RE_Offset_To_Top_Ptr
)
570 -- Otherwise go ahead and install the check
572 Install_Null_Excluding_Check
(P
);
573 end Apply_Access_Check
;
575 --------------------------------
576 -- Apply_Address_Clause_Check --
577 --------------------------------
579 procedure Apply_Address_Clause_Check
(E
: Entity_Id
; N
: Node_Id
) is
580 pragma Assert
(Nkind
(N
) = N_Freeze_Entity
);
582 AC
: constant Node_Id
:= Address_Clause
(E
);
583 Loc
: constant Source_Ptr
:= Sloc
(AC
);
584 Typ
: constant Entity_Id
:= Etype
(E
);
587 -- Address expression (not necessarily the same as Aexp, for example
588 -- when Aexp is a reference to a constant, in which case Expr gets
589 -- reset to reference the value expression of the constant).
592 -- See if alignment check needed. Note that we never need a check if the
593 -- maximum alignment is one, since the check will always succeed.
595 -- Note: we do not check for checks suppressed here, since that check
596 -- was done in Sem_Ch13 when the address clause was processed. We are
597 -- only called if checks were not suppressed. The reason for this is
598 -- that we have to delay the call to Apply_Alignment_Check till freeze
599 -- time (so that all types etc are elaborated), but we have to check
600 -- the status of check suppressing at the point of the address clause.
603 or else not Check_Address_Alignment
(AC
)
604 or else Maximum_Alignment
= 1
609 -- Obtain expression from address clause
611 Expr
:= Address_Value
(Expression
(AC
));
613 -- See if we know that Expr has an acceptable value at compile time. If
614 -- it hasn't or we don't know, we defer issuing the warning until the
615 -- end of the compilation to take into account back end annotations.
617 if Compile_Time_Known_Value
(Expr
)
618 and then (Known_Alignment
(E
) or else Known_Alignment
(Typ
))
621 AL
: Uint
:= Alignment
(Typ
);
624 -- The object alignment might be more restrictive than the type
627 if Known_Alignment
(E
) then
631 if Expr_Value
(Expr
) mod AL
= 0 then
636 -- If the expression has the form X'Address, then we can find out if the
637 -- object X has an alignment that is compatible with the object E. If it
638 -- hasn't or we don't know, we defer issuing the warning until the end
639 -- of the compilation to take into account back end annotations.
641 elsif Nkind
(Expr
) = N_Attribute_Reference
642 and then Attribute_Name
(Expr
) = Name_Address
644 Has_Compatible_Alignment
(E
, Prefix
(Expr
), False) = Known_Compatible
649 -- Here we do not know if the value is acceptable. Strictly we don't
650 -- have to do anything, since if the alignment is bad, we have an
651 -- erroneous program. However we are allowed to check for erroneous
652 -- conditions and we decide to do this by default if the check is not
655 -- However, don't do the check if elaboration code is unwanted
657 if Restriction_Active
(No_Elaboration_Code
) then
660 -- Generate a check to raise PE if alignment may be inappropriate
663 -- If the original expression is a nonstatic constant, use the name
664 -- of the constant itself rather than duplicating its initialization
665 -- expression, which was extracted above.
667 -- Note: Expr is empty if the address-clause is applied to in-mode
668 -- actuals (allowed by 13.1(22)).
672 (Is_Entity_Name
(Expression
(AC
))
673 and then Ekind
(Entity
(Expression
(AC
))) = E_Constant
674 and then Nkind
(Parent
(Entity
(Expression
(AC
)))) =
675 N_Object_Declaration
)
677 Expr
:= New_Copy_Tree
(Expression
(AC
));
679 Remove_Side_Effects
(Expr
);
682 if No
(Actions
(N
)) then
683 Set_Actions
(N
, New_List
);
686 Prepend_To
(Actions
(N
),
687 Make_Raise_Program_Error
(Loc
,
694 (RTE
(RE_Integer_Address
), Expr
),
696 Make_Attribute_Reference
(Loc
,
697 Prefix
=> New_Occurrence_Of
(E
, Loc
),
698 Attribute_Name
=> Name_Alignment
)),
699 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
)),
700 Reason
=> PE_Misaligned_Address_Value
));
702 Warning_Msg
:= No_Error_Msg
;
703 Analyze
(First
(Actions
(N
)), Suppress
=> All_Checks
);
705 -- If the above raise action generated a warning message (for example
706 -- from Warn_On_Non_Local_Exception mode with the active restriction
707 -- No_Exception_Propagation).
709 if Warning_Msg
/= No_Error_Msg
then
711 -- If the expression has a known at compile time value, then
712 -- once we know the alignment of the type, we can check if the
713 -- exception will be raised or not, and if not, we don't need
714 -- the warning so we will kill the warning later on.
716 if Compile_Time_Known_Value
(Expr
) then
717 Alignment_Warnings
.Append
719 A
=> Expr_Value
(Expr
),
723 -- Likewise if the expression is of the form X'Address
725 elsif Nkind
(Expr
) = N_Attribute_Reference
726 and then Attribute_Name
(Expr
) = Name_Address
728 Alignment_Warnings
.Append
734 -- Add explanation of the warning generated by the check
738 ("\address value may be incompatible with alignment of "
748 -- If we have some missing run time component in configurable run time
749 -- mode then just skip the check (it is not required in any case).
751 when RE_Not_Available
=>
753 end Apply_Address_Clause_Check
;
755 -------------------------------------
756 -- Apply_Arithmetic_Overflow_Check --
757 -------------------------------------
759 procedure Apply_Arithmetic_Overflow_Check
(N
: Node_Id
) is
761 -- Use old routine in almost all cases (the only case we are treating
762 -- specially is the case of a signed integer arithmetic op with the
763 -- overflow checking mode set to MINIMIZED or ELIMINATED).
765 if Overflow_Check_Mode
= Strict
766 or else not Is_Signed_Integer_Arithmetic_Op
(N
)
768 Apply_Arithmetic_Overflow_Strict
(N
);
770 -- Otherwise use the new routine for the case of a signed integer
771 -- arithmetic op, with Do_Overflow_Check set to True, and the checking
772 -- mode is MINIMIZED or ELIMINATED.
775 Apply_Arithmetic_Overflow_Minimized_Eliminated
(N
);
777 end Apply_Arithmetic_Overflow_Check
;
779 --------------------------------------
780 -- Apply_Arithmetic_Overflow_Strict --
781 --------------------------------------
783 -- This routine is called only if the type is an integer type and an
784 -- arithmetic overflow check may be needed for op (add, subtract, or
785 -- multiply). This check is performed if Backend_Overflow_Checks_On_Target
786 -- is not enabled and Do_Overflow_Check is set. In this case we expand the
787 -- operation into a more complex sequence of tests that ensures that
788 -- overflow is properly caught.
790 -- This is used in CHECKED modes. It is identical to the code for this
791 -- cases before the big overflow earthquake, thus ensuring that in this
792 -- modes we have compatible behavior (and reliability) to what was there
793 -- before. It is also called for types other than signed integers, and if
794 -- the Do_Overflow_Check flag is off.
796 -- Note: we also call this routine if we decide in the MINIMIZED case
797 -- to give up and just generate an overflow check without any fuss.
799 procedure Apply_Arithmetic_Overflow_Strict
(N
: Node_Id
) is
800 Loc
: constant Source_Ptr
:= Sloc
(N
);
801 Typ
: constant Entity_Id
:= Etype
(N
);
802 Rtyp
: constant Entity_Id
:= Root_Type
(Typ
);
805 -- Nothing to do if Do_Overflow_Check not set or overflow checks
808 if not Do_Overflow_Check
(N
) then
812 -- An interesting special case. If the arithmetic operation appears as
813 -- the operand of a type conversion:
817 -- and all the following conditions apply:
819 -- arithmetic operation is for a signed integer type
820 -- target type type1 is a static integer subtype
821 -- range of x and y are both included in the range of type1
822 -- range of x op y is included in the range of type1
823 -- size of type1 is at least twice the result size of op
825 -- then we don't do an overflow check in any case. Instead, we transform
826 -- the operation so that we end up with:
828 -- type1 (type1 (x) op type1 (y))
830 -- This avoids intermediate overflow before the conversion. It is
831 -- explicitly permitted by RM 3.5.4(24):
833 -- For the execution of a predefined operation of a signed integer
834 -- type, the implementation need not raise Constraint_Error if the
835 -- result is outside the base range of the type, so long as the
836 -- correct result is produced.
838 -- It's hard to imagine that any programmer counts on the exception
839 -- being raised in this case, and in any case it's wrong coding to
840 -- have this expectation, given the RM permission. Furthermore, other
841 -- Ada compilers do allow such out of range results.
843 -- Note that we do this transformation even if overflow checking is
844 -- off, since this is precisely about giving the "right" result and
845 -- avoiding the need for an overflow check.
847 -- Note: this circuit is partially redundant with respect to the similar
848 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
849 -- with cases that do not come through here. We still need the following
850 -- processing even with the Exp_Ch4 code in place, since we want to be
851 -- sure not to generate the arithmetic overflow check in these cases
852 -- (Exp_Ch4 would have a hard time removing them once generated).
854 if Is_Signed_Integer_Type
(Typ
)
855 and then Nkind
(Parent
(N
)) = N_Type_Conversion
857 Conversion_Optimization
: declare
858 Target_Type
: constant Entity_Id
:=
859 Base_Type
(Entity
(Subtype_Mark
(Parent
(N
))));
873 if Is_Integer_Type
(Target_Type
)
874 and then RM_Size
(Root_Type
(Target_Type
)) >= 2 * RM_Size
(Rtyp
)
876 Tlo
:= Expr_Value
(Type_Low_Bound
(Target_Type
));
877 Thi
:= Expr_Value
(Type_High_Bound
(Target_Type
));
880 (Left_Opnd
(N
), LOK
, Llo
, Lhi
, Assume_Valid
=> True);
882 (Right_Opnd
(N
), ROK
, Rlo
, Rhi
, Assume_Valid
=> True);
885 and then Tlo
<= Llo
and then Lhi
<= Thi
886 and then Tlo
<= Rlo
and then Rhi
<= Thi
888 Determine_Range
(N
, VOK
, Vlo
, Vhi
, Assume_Valid
=> True);
890 if VOK
and then Tlo
<= Vlo
and then Vhi
<= Thi
then
891 -- Rewrite the conversion operand so that the original
892 -- node is retained, in order to avoid the warning for
893 -- redundant conversions in Resolve_Type_Conversion.
896 Op
: constant Node_Id
:= New_Op_Node
(Nkind
(N
), Loc
);
899 Make_Type_Conversion
(Loc
,
901 New_Occurrence_Of
(Target_Type
, Loc
),
902 Expression
=> Relocate_Node
(Left_Opnd
(N
))));
904 Make_Type_Conversion
(Loc
,
906 New_Occurrence_Of
(Target_Type
, Loc
),
907 Expression
=> Relocate_Node
(Right_Opnd
(N
))));
912 Set_Etype
(N
, Target_Type
);
914 Analyze_And_Resolve
(Left_Opnd
(N
), Target_Type
);
915 Analyze_And_Resolve
(Right_Opnd
(N
), Target_Type
);
917 -- Given that the target type is twice the size of the
918 -- source type, overflow is now impossible, so we can
919 -- safely kill the overflow check and return.
921 Set_Do_Overflow_Check
(N
, False);
926 end Conversion_Optimization
;
929 -- Now see if an overflow check is required
932 Dsiz
: constant Uint
:= 2 * Esize
(Rtyp
);
939 -- Skip check if back end does overflow checks, or the overflow flag
940 -- is not set anyway, or we are not doing code expansion, or the
941 -- parent node is a type conversion whose operand is an arithmetic
942 -- operation on signed integers on which the expander can promote
943 -- later the operands to type Integer (see Expand_N_Type_Conversion).
945 if Backend_Overflow_Checks_On_Target
946 or else not Do_Overflow_Check
(N
)
947 or else not Expander_Active
948 or else (Present
(Parent
(N
))
949 and then Nkind
(Parent
(N
)) = N_Type_Conversion
950 and then Integer_Promotion_Possible
(Parent
(N
)))
955 -- Otherwise, generate the full general code for front end overflow
956 -- detection, which works by doing arithmetic in a larger type:
962 -- Typ (Checktyp (x) op Checktyp (y));
964 -- where Typ is the type of the original expression, and Checktyp is
965 -- an integer type of sufficient length to hold the largest possible
968 -- If the size of the check type exceeds the maximum integer size,
969 -- we use a different approach, expanding to:
971 -- typ (xxx_With_Ovflo_Check (Integer_NN (x), Integer_NN (y)))
973 -- where xxx is Add, Multiply or Subtract as appropriate
975 -- Find check type if one exists
977 if Dsiz
<= System_Max_Integer_Size
then
978 Ctyp
:= Integer_Type_For
(Dsiz
, Uns
=> False);
980 -- No check type exists, use runtime call
983 if System_Max_Integer_Size
= 64 then
984 Ctyp
:= RTE
(RE_Integer_64
);
986 Ctyp
:= RTE
(RE_Integer_128
);
989 if Nkind
(N
) = N_Op_Add
then
990 if System_Max_Integer_Size
= 64 then
991 Cent
:= RE_Add_With_Ovflo_Check64
;
993 Cent
:= RE_Add_With_Ovflo_Check128
;
996 elsif Nkind
(N
) = N_Op_Subtract
then
997 if System_Max_Integer_Size
= 64 then
998 Cent
:= RE_Subtract_With_Ovflo_Check64
;
1000 Cent
:= RE_Subtract_With_Ovflo_Check128
;
1003 else pragma Assert
(Nkind
(N
) = N_Op_Multiply
);
1004 if System_Max_Integer_Size
= 64 then
1005 Cent
:= RE_Multiply_With_Ovflo_Check64
;
1007 Cent
:= RE_Multiply_With_Ovflo_Check128
;
1013 Make_Function_Call
(Loc
,
1014 Name
=> New_Occurrence_Of
(RTE
(Cent
), Loc
),
1015 Parameter_Associations
=> New_List
(
1016 OK_Convert_To
(Ctyp
, Left_Opnd
(N
)),
1017 OK_Convert_To
(Ctyp
, Right_Opnd
(N
))))));
1019 Analyze_And_Resolve
(N
, Typ
);
1023 -- If we fall through, we have the case where we do the arithmetic
1024 -- in the next higher type and get the check by conversion. In these
1025 -- cases Ctyp is set to the type to be used as the check type.
1027 Opnod
:= Relocate_Node
(N
);
1029 Opnd
:= OK_Convert_To
(Ctyp
, Left_Opnd
(Opnod
));
1032 Set_Etype
(Opnd
, Ctyp
);
1033 Set_Analyzed
(Opnd
, True);
1034 Set_Left_Opnd
(Opnod
, Opnd
);
1036 Opnd
:= OK_Convert_To
(Ctyp
, Right_Opnd
(Opnod
));
1039 Set_Etype
(Opnd
, Ctyp
);
1040 Set_Analyzed
(Opnd
, True);
1041 Set_Right_Opnd
(Opnod
, Opnd
);
1043 -- The type of the operation changes to the base type of the check
1044 -- type, and we reset the overflow check indication, since clearly no
1045 -- overflow is possible now that we are using a double length type.
1046 -- We also set the Analyzed flag to avoid a recursive attempt to
1049 Set_Etype
(Opnod
, Base_Type
(Ctyp
));
1050 Set_Do_Overflow_Check
(Opnod
, False);
1051 Set_Analyzed
(Opnod
, True);
1053 -- Now build the outer conversion
1055 Opnd
:= OK_Convert_To
(Typ
, Opnod
);
1057 Set_Etype
(Opnd
, Typ
);
1059 -- In the discrete type case, we directly generate the range check
1060 -- for the outer operand. This range check will implement the
1061 -- required overflow check.
1063 if Is_Discrete_Type
(Typ
) then
1065 Generate_Range_Check
1066 (Expression
(N
), Typ
, CE_Overflow_Check_Failed
);
1068 -- For other types, we enable overflow checking on the conversion,
1069 -- after setting the node as analyzed to prevent recursive attempts
1070 -- to expand the conversion node.
1073 Set_Analyzed
(Opnd
, True);
1074 Enable_Overflow_Check
(Opnd
);
1079 when RE_Not_Available
=>
1082 end Apply_Arithmetic_Overflow_Strict
;
1084 ----------------------------------------------------
1085 -- Apply_Arithmetic_Overflow_Minimized_Eliminated --
1086 ----------------------------------------------------
1088 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated
(Op
: Node_Id
) is
1089 pragma Assert
(Is_Signed_Integer_Arithmetic_Op
(Op
));
1091 Loc
: constant Source_Ptr
:= Sloc
(Op
);
1092 P
: constant Node_Id
:= Parent
(Op
);
1094 LLIB
: constant Entity_Id
:= Base_Type
(Standard_Long_Long_Integer
);
1095 -- Operands and results are of this type when we convert
1097 Result_Type
: constant Entity_Id
:= Etype
(Op
);
1098 -- Original result type
1100 Check_Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
1101 pragma Assert
(Check_Mode
in Minimized_Or_Eliminated
);
1104 -- Ranges of values for result
1107 -- Nothing to do if our parent is one of the following:
1109 -- Another signed integer arithmetic op
1110 -- A membership operation
1111 -- A comparison operation
1113 -- In all these cases, we will process at the higher level (and then
1114 -- this node will be processed during the downwards recursion that
1115 -- is part of the processing in Minimize_Eliminate_Overflows).
1117 if Is_Signed_Integer_Arithmetic_Op
(P
)
1118 or else Nkind
(P
) in N_Membership_Test
1119 or else Nkind
(P
) in N_Op_Compare
1121 -- This is also true for an alternative in a case expression
1123 or else Nkind
(P
) = N_Case_Expression_Alternative
1125 -- This is also true for a range operand in a membership test
1127 or else (Nkind
(P
) = N_Range
1128 and then Nkind
(Parent
(P
)) in N_Membership_Test
)
1130 -- If_Expressions and Case_Expressions are treated as arithmetic
1131 -- ops, but if they appear in an assignment or similar contexts
1132 -- there is no overflow check that starts from that parent node,
1133 -- so apply check now.
1134 -- Similarly, if these expressions are nested, we should go on.
1136 if Nkind
(P
) in N_If_Expression | N_Case_Expression
1137 and then not Is_Signed_Integer_Arithmetic_Op
(Parent
(P
))
1140 elsif Nkind
(P
) in N_If_Expression | N_Case_Expression
1141 and then Nkind
(Op
) in N_If_Expression | N_Case_Expression
1149 -- Otherwise, we have a top level arithmetic operation node, and this
1150 -- is where we commence the special processing for MINIMIZED/ELIMINATED
1151 -- modes. This is the case where we tell the machinery not to move into
1152 -- Bignum mode at this top level (of course the top level operation
1153 -- will still be in Bignum mode if either of its operands are of type
1156 Minimize_Eliminate_Overflows
(Op
, Lo
, Hi
, Top_Level
=> True);
1158 -- That call may but does not necessarily change the result type of Op.
1159 -- It is the job of this routine to undo such changes, so that at the
1160 -- top level, we have the proper type. This "undoing" is a point at
1161 -- which a final overflow check may be applied.
1163 -- If the result type was not fiddled we are all set. We go to base
1164 -- types here because things may have been rewritten to generate the
1165 -- base type of the operand types.
1167 if Base_Type
(Etype
(Op
)) = Base_Type
(Result_Type
) then
1172 elsif Is_RTE
(Etype
(Op
), RE_Bignum
) then
1174 -- We need a sequence that looks like:
1176 -- Rnn : Result_Type;
1179 -- M : Mark_Id := SS_Mark;
1181 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
1185 -- This block is inserted (using Insert_Actions), and then the node
1186 -- is replaced with a reference to Rnn.
1188 -- If our parent is a conversion node then there is no point in
1189 -- generating a conversion to Result_Type. Instead, we let the parent
1190 -- handle this. Note that this special case is not just about
1191 -- optimization. Consider
1195 -- X := Long_Long_Integer'Base (A * (B ** C));
1197 -- Now the product may fit in Long_Long_Integer but not in Integer.
1198 -- In MINIMIZED/ELIMINATED mode, we don't want to introduce an
1199 -- overflow exception for this intermediate value.
1202 Blk
: constant Node_Id
:= Make_Bignum_Block
(Loc
);
1203 Rnn
: constant Entity_Id
:= Make_Temporary
(Loc
, 'R', Op
);
1209 RHS
:= Convert_From_Bignum
(Op
);
1211 if Nkind
(P
) /= N_Type_Conversion
then
1212 Convert_To_And_Rewrite
(Result_Type
, RHS
);
1213 Rtype
:= Result_Type
;
1215 -- Interesting question, do we need a check on that conversion
1216 -- operation. Answer, not if we know the result is in range.
1217 -- At the moment we are not taking advantage of this. To be
1218 -- looked at later ???
1225 (First
(Statements
(Handled_Statement_Sequence
(Blk
))),
1226 Make_Assignment_Statement
(Loc
,
1227 Name
=> New_Occurrence_Of
(Rnn
, Loc
),
1228 Expression
=> RHS
));
1230 Insert_Actions
(Op
, New_List
(
1231 Make_Object_Declaration
(Loc
,
1232 Defining_Identifier
=> Rnn
,
1233 Object_Definition
=> New_Occurrence_Of
(Rtype
, Loc
)),
1236 Rewrite
(Op
, New_Occurrence_Of
(Rnn
, Loc
));
1237 Analyze_And_Resolve
(Op
);
1240 -- Here we know the result is Long_Long_Integer'Base, or that it has
1241 -- been rewritten because the parent operation is a conversion. See
1242 -- Apply_Arithmetic_Overflow_Strict.Conversion_Optimization.
1246 (Etype
(Op
) = LLIB
or else Nkind
(Parent
(Op
)) = N_Type_Conversion
);
1248 -- All we need to do here is to convert the result to the proper
1249 -- result type. As explained above for the Bignum case, we can
1250 -- omit this if our parent is a type conversion.
1252 if Nkind
(P
) /= N_Type_Conversion
then
1253 Convert_To_And_Rewrite
(Result_Type
, Op
);
1256 Analyze_And_Resolve
(Op
);
1258 end Apply_Arithmetic_Overflow_Minimized_Eliminated
;
1260 ----------------------------
1261 -- Apply_Constraint_Check --
1262 ----------------------------
1264 procedure Apply_Constraint_Check
1267 No_Sliding
: Boolean := False)
1269 Desig_Typ
: Entity_Id
;
1272 -- No checks inside a generic (check the instantiations)
1274 if Inside_A_Generic
then
1278 -- Apply required constraint checks
1280 if Is_Scalar_Type
(Typ
) then
1281 Apply_Scalar_Range_Check
(N
, Typ
);
1283 elsif Is_Array_Type
(Typ
) then
1285 -- A useful optimization: an aggregate with only an others clause
1286 -- always has the right bounds.
1288 if Nkind
(N
) = N_Aggregate
1289 and then No
(Expressions
(N
))
1290 and then Nkind
(First
(Component_Associations
(N
))) =
1291 N_Component_Association
1293 (First
(Choices
(First
(Component_Associations
(N
)))))
1299 if Is_Constrained
(Typ
) then
1300 Apply_Length_Check
(N
, Typ
);
1303 Apply_Range_Check
(N
, Typ
);
1306 Apply_Range_Check
(N
, Typ
);
1309 elsif (Is_Record_Type
(Typ
) or else Is_Private_Type
(Typ
))
1310 and then Has_Discriminants
(Base_Type
(Typ
))
1311 and then Is_Constrained
(Typ
)
1313 Apply_Discriminant_Check
(N
, Typ
);
1315 elsif Is_Access_Type
(Typ
) then
1317 Desig_Typ
:= Designated_Type
(Typ
);
1319 -- No checks necessary if expression statically null
1321 if Known_Null
(N
) then
1322 if Can_Never_Be_Null
(Typ
) then
1323 Install_Null_Excluding_Check
(N
);
1326 -- No sliding possible on access to arrays
1328 elsif Is_Array_Type
(Desig_Typ
) then
1329 if Is_Constrained
(Desig_Typ
) then
1330 Apply_Length_Check
(N
, Typ
);
1333 Apply_Range_Check
(N
, Typ
);
1335 -- Do not install a discriminant check for a constrained subtype
1336 -- created for an unconstrained nominal type because the subtype
1337 -- has the correct constraints by construction.
1339 elsif Has_Discriminants
(Base_Type
(Desig_Typ
))
1340 and then Is_Constrained
(Desig_Typ
)
1341 and then not Is_Constr_Subt_For_U_Nominal
(Desig_Typ
)
1343 Apply_Discriminant_Check
(N
, Typ
);
1346 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1347 -- this check if the constraint node is illegal, as shown by having
1348 -- an error posted. This additional guard prevents cascaded errors
1349 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1351 if Can_Never_Be_Null
(Typ
)
1352 and then not Can_Never_Be_Null
(Etype
(N
))
1353 and then not Error_Posted
(N
)
1355 Install_Null_Excluding_Check
(N
);
1358 end Apply_Constraint_Check
;
1360 ------------------------------
1361 -- Apply_Discriminant_Check --
1362 ------------------------------
1364 procedure Apply_Discriminant_Check
1367 Lhs
: Node_Id
:= Empty
)
1369 Loc
: constant Source_Ptr
:= Sloc
(N
);
1370 Do_Access
: constant Boolean := Is_Access_Type
(Typ
);
1371 S_Typ
: Entity_Id
:= Etype
(N
);
1375 function Denotes_Explicit_Dereference
(Obj
: Node_Id
) return Boolean;
1376 -- A heap object with an indefinite subtype is constrained by its
1377 -- initial value, and assigning to it requires a constraint_check.
1378 -- The target may be an explicit dereference, or a renaming of one.
1380 function Is_Aliased_Unconstrained_Component
return Boolean;
1381 -- It is possible for an aliased component to have a nominal
1382 -- unconstrained subtype (through instantiation). If this is a
1383 -- discriminated component assigned in the expansion of an aggregate
1384 -- in an initialization, the check must be suppressed. This unusual
1385 -- situation requires a predicate of its own.
1387 ----------------------------------
1388 -- Denotes_Explicit_Dereference --
1389 ----------------------------------
1391 function Denotes_Explicit_Dereference
(Obj
: Node_Id
) return Boolean is
1393 if Is_Entity_Name
(Obj
) then
1394 return Present
(Renamed_Object
(Entity
(Obj
)))
1396 Denotes_Explicit_Dereference
(Renamed_Object
(Entity
(Obj
)));
1398 -- This routine uses the rules of the language so we need to exclude
1399 -- rewritten constructs that introduce artificial dereferences.
1401 elsif Nkind
(Obj
) = N_Explicit_Dereference
then
1402 return not Is_Captured_Function_Call
(Obj
)
1404 (Nkind
(Parent
(Obj
)) = N_Object_Renaming_Declaration
1405 and then Is_Return_Object
(Defining_Entity
(Parent
(Obj
))));
1410 end Denotes_Explicit_Dereference
;
1412 ----------------------------------------
1413 -- Is_Aliased_Unconstrained_Component --
1414 ----------------------------------------
1416 function Is_Aliased_Unconstrained_Component
return Boolean is
1421 if Nkind
(Lhs
) /= N_Selected_Component
then
1424 Comp
:= Entity
(Selector_Name
(Lhs
));
1425 Pref
:= Prefix
(Lhs
);
1428 if Ekind
(Comp
) /= E_Component
1429 or else not Is_Aliased
(Comp
)
1434 return not Comes_From_Source
(Pref
)
1435 and then In_Instance
1436 and then not Is_Constrained
(Etype
(Comp
));
1437 end Is_Aliased_Unconstrained_Component
;
1439 -- Start of processing for Apply_Discriminant_Check
1443 T_Typ
:= Designated_Type
(Typ
);
1448 -- If the expression is a function call that returns a limited object
1449 -- it cannot be copied. It is not clear how to perform the proper
1450 -- discriminant check in this case because the discriminant value must
1451 -- be retrieved from the constructed object itself.
1453 if Nkind
(N
) = N_Function_Call
1454 and then Is_Limited_Type
(Typ
)
1455 and then Is_Entity_Name
(Name
(N
))
1456 and then Returns_By_Ref
(Entity
(Name
(N
)))
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
)))
1514 T_Typ
:= Get_Actual_Subtype
(Lhs
);
1517 -- Nothing to do if the type is unconstrained (this is the case where
1518 -- the actual subtype in the RM sense of N is unconstrained and no check
1521 if not Is_Constrained
(T_Typ
) then
1524 -- Ada 2005: nothing to do if the type is one for which there is a
1525 -- partial view that is constrained.
1527 elsif Ada_Version
>= Ada_2005
1528 and then Object_Type_Has_Constrained_Partial_View
1529 (Typ
=> Base_Type
(T_Typ
),
1530 Scop
=> Current_Scope
)
1535 -- Nothing to do if the type is an Unchecked_Union
1537 if Is_Unchecked_Union
(Base_Type
(T_Typ
)) then
1541 -- Suppress checks if the subtypes are the same. The check must be
1542 -- preserved in an assignment to a formal, because the constraint is
1543 -- given by the actual.
1545 if Nkind
(Original_Node
(N
)) /= N_Allocator
1547 or else not Is_Entity_Name
(Lhs
)
1548 or else No
(Param_Entity
(Lhs
)))
1551 or else (Do_Access
and then Designated_Type
(Typ
) = S_Typ
))
1552 and then not Is_Aliased_View
(Lhs
)
1557 -- We can also eliminate checks on allocators with a subtype mark that
1558 -- coincides with the context type. The context type may be a subtype
1559 -- without a constraint (common case, a generic actual).
1561 elsif Nkind
(Original_Node
(N
)) = N_Allocator
1562 and then Is_Entity_Name
(Expression
(Original_Node
(N
)))
1565 Alloc_Typ
: constant Entity_Id
:=
1566 Entity
(Expression
(Original_Node
(N
)));
1569 if Alloc_Typ
= T_Typ
1570 or else (Nkind
(Parent
(T_Typ
)) = N_Subtype_Declaration
1571 and then Is_Entity_Name
(
1572 Subtype_Indication
(Parent
(T_Typ
)))
1573 and then Alloc_Typ
= Base_Type
(T_Typ
))
1581 -- See if we have a case where the types are both constrained, and all
1582 -- the constraints are constants. In this case, we can do the check
1583 -- successfully at compile time.
1585 -- We skip this check for the case where the node is rewritten as
1586 -- an allocator, because it already carries the context subtype,
1587 -- and extracting the discriminants from the aggregate is messy.
1589 if Is_Constrained
(S_Typ
)
1590 and then Nkind
(Original_Node
(N
)) /= N_Allocator
1600 -- S_Typ may not have discriminants in the case where it is a
1601 -- private type completed by a default discriminated type. In that
1602 -- case, we need to get the constraints from the underlying type.
1603 -- If the underlying type is unconstrained (i.e. has no default
1604 -- discriminants) no check is needed.
1606 if Has_Discriminants
(S_Typ
) then
1607 Discr
:= First_Discriminant
(S_Typ
);
1608 DconS
:= First_Elmt
(Discriminant_Constraint
(S_Typ
));
1611 Discr
:= First_Discriminant
(Underlying_Type
(S_Typ
));
1614 (Discriminant_Constraint
(Underlying_Type
(S_Typ
)));
1620 -- A further optimization: if T_Typ is derived from S_Typ
1621 -- without imposing a constraint, no check is needed.
1623 if Nkind
(Original_Node
(Parent
(T_Typ
))) =
1624 N_Full_Type_Declaration
1627 Type_Def
: constant Node_Id
:=
1628 Type_Definition
(Original_Node
(Parent
(T_Typ
)));
1630 if Nkind
(Type_Def
) = N_Derived_Type_Definition
1631 and then Is_Entity_Name
(Subtype_Indication
(Type_Def
))
1632 and then Entity
(Subtype_Indication
(Type_Def
)) = S_Typ
1640 -- Constraint may appear in full view of type
1642 if Ekind
(T_Typ
) = E_Private_Subtype
1643 and then Present
(Full_View
(T_Typ
))
1646 First_Elmt
(Discriminant_Constraint
(Full_View
(T_Typ
)));
1649 First_Elmt
(Discriminant_Constraint
(T_Typ
));
1652 while Present
(Discr
) loop
1653 ItemS
:= Node
(DconS
);
1654 ItemT
:= Node
(DconT
);
1656 -- For a discriminated component type constrained by the
1657 -- current instance of an enclosing type, there is no
1658 -- applicable discriminant check.
1660 if Nkind
(ItemT
) = N_Attribute_Reference
1661 and then Is_Access_Type
(Etype
(ItemT
))
1662 and then Is_Entity_Name
(Prefix
(ItemT
))
1663 and then Is_Type
(Entity
(Prefix
(ItemT
)))
1668 -- If the expressions for the discriminants are identical
1669 -- and it is side-effect-free (for now just an entity),
1670 -- this may be a shared constraint, e.g. from a subtype
1671 -- without a constraint introduced as a generic actual.
1672 -- Examine other discriminants if any.
1675 and then Is_Entity_Name
(ItemS
)
1679 elsif not Is_OK_Static_Expression
(ItemS
)
1680 or else not Is_OK_Static_Expression
(ItemT
)
1684 elsif Expr_Value
(ItemS
) /= Expr_Value
(ItemT
) then
1685 if Do_Access
then -- needs run-time check.
1688 Apply_Compile_Time_Constraint_Error
1689 (N
, "incorrect value for discriminant&??",
1690 CE_Discriminant_Check_Failed
, Ent
=> Discr
);
1697 Next_Discriminant
(Discr
);
1706 -- In GNATprove mode, we do not apply the checks
1708 if GNATprove_Mode
then
1712 -- Here we need a discriminant check. First build the expression
1713 -- for the comparisons of the discriminants:
1715 -- (n.disc1 /= typ.disc1) or else
1716 -- (n.disc2 /= typ.disc2) or else
1718 -- (n.discn /= typ.discn)
1720 Cond
:= Build_Discriminant_Checks
(N
, T_Typ
);
1722 -- If Lhs is set and is a parameter, then the condition is guarded by:
1723 -- lhs'constrained and then (condition built above)
1725 if Present
(Param_Entity
(Lhs
)) then
1729 Make_Attribute_Reference
(Loc
,
1730 Prefix
=> New_Occurrence_Of
(Param_Entity
(Lhs
), Loc
),
1731 Attribute_Name
=> Name_Constrained
),
1732 Right_Opnd
=> Cond
);
1736 Cond
:= Guard_Access
(Cond
, Loc
, N
);
1740 Make_Raise_Constraint_Error
(Loc
,
1742 Reason
=> CE_Discriminant_Check_Failed
));
1743 end Apply_Discriminant_Check
;
1745 -------------------------
1746 -- Apply_Divide_Checks --
1747 -------------------------
1749 procedure Apply_Divide_Checks
(N
: Node_Id
) is
1750 Loc
: constant Source_Ptr
:= Sloc
(N
);
1751 Typ
: constant Entity_Id
:= Etype
(N
);
1752 Left
: constant Node_Id
:= Left_Opnd
(N
);
1753 Right
: constant Node_Id
:= Right_Opnd
(N
);
1755 Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
1756 -- Current overflow checking mode
1766 pragma Warnings
(Off
, Lhi
);
1767 -- Don't actually use this value
1770 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1771 -- operating on signed integer types, then the only thing this routine
1772 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1773 -- procedure will (possibly later on during recursive downward calls),
1774 -- ensure that any needed overflow/division checks are properly applied.
1776 if Mode
in Minimized_Or_Eliminated
1777 and then Is_Signed_Integer_Type
(Typ
)
1779 Apply_Arithmetic_Overflow_Minimized_Eliminated
(N
);
1783 -- Proceed here in SUPPRESSED or CHECKED modes
1786 and then not Backend_Divide_Checks_On_Target
1787 and then Check_Needed
(Right
, Division_Check
)
1789 Determine_Range
(Right
, ROK
, Rlo
, Rhi
, Assume_Valid
=> True);
1791 -- Deal with division check
1793 if Do_Division_Check
(N
)
1794 and then not Division_Checks_Suppressed
(Typ
)
1796 Apply_Division_Check
(N
, Rlo
, Rhi
, ROK
);
1799 -- Deal with overflow check
1801 if Do_Overflow_Check
(N
)
1802 and then not Overflow_Checks_Suppressed
(Etype
(N
))
1804 Set_Do_Overflow_Check
(N
, False);
1806 -- Test for extremely annoying case of xxx'First divided by -1
1807 -- for division of signed integer types (only overflow case).
1809 if Nkind
(N
) = N_Op_Divide
1810 and then Is_Signed_Integer_Type
(Typ
)
1812 Determine_Range
(Left
, LOK
, Llo
, Lhi
, Assume_Valid
=> True);
1813 LLB
:= Expr_Value
(Type_Low_Bound
(Base_Type
(Typ
)));
1815 if (not ROK
or else (Rlo
<= (-1) and then (-1) <= Rhi
))
1817 (not LOK
or else Llo
= LLB
)
1819 -- Ensure that expressions are not evaluated twice (once
1820 -- for their runtime checks and once for their regular
1823 Force_Evaluation
(Left
, Mode
=> Strict
);
1824 Force_Evaluation
(Right
, Mode
=> Strict
);
1827 Make_Raise_Constraint_Error
(Loc
,
1833 Duplicate_Subexpr_Move_Checks
(Left
),
1834 Right_Opnd
=> Make_Integer_Literal
(Loc
, LLB
)),
1838 Left_Opnd
=> Duplicate_Subexpr
(Right
),
1839 Right_Opnd
=> Make_Integer_Literal
(Loc
, -1))),
1841 Reason
=> CE_Overflow_Check_Failed
));
1846 end Apply_Divide_Checks
;
1848 --------------------------
1849 -- Apply_Division_Check --
1850 --------------------------
1852 procedure Apply_Division_Check
1858 pragma Assert
(Do_Division_Check
(N
));
1860 Loc
: constant Source_Ptr
:= Sloc
(N
);
1861 Right
: constant Node_Id
:= Right_Opnd
(N
);
1866 and then not Backend_Divide_Checks_On_Target
1867 and then Check_Needed
(Right
, Division_Check
)
1869 -- See if division by zero possible, and if so generate test. This
1870 -- part of the test is not controlled by the -gnato switch, since it
1871 -- is a Division_Check and not an Overflow_Check.
1873 and then Do_Division_Check
(N
)
1875 Set_Do_Division_Check
(N
, False);
1877 if not ROK
or else (Rlo
<= 0 and then 0 <= Rhi
) then
1878 if Is_Floating_Point_Type
(Etype
(N
)) then
1879 Opnd
:= Make_Real_Literal
(Loc
, Ureal_0
);
1881 Opnd
:= Make_Integer_Literal
(Loc
, 0);
1885 Make_Raise_Constraint_Error
(Loc
,
1888 Left_Opnd
=> Duplicate_Subexpr_Move_Checks
(Right
),
1889 Right_Opnd
=> Opnd
),
1890 Reason
=> CE_Divide_By_Zero
));
1893 end Apply_Division_Check
;
1895 ----------------------------------
1896 -- Apply_Float_Conversion_Check --
1897 ----------------------------------
1899 -- Let F and I be the source and target types of the conversion. The RM
1900 -- specifies that a floating-point value X is rounded to the nearest
1901 -- integer, with halfway cases being rounded away from zero. The rounded
1902 -- value of X is checked against I'Range.
1904 -- The catch in the above paragraph is that there is no good way to know
1905 -- whether the round-to-integer operation resulted in overflow. A remedy is
1906 -- to perform a range check in the floating-point domain instead, however:
1908 -- (1) The bounds may not be known at compile time
1909 -- (2) The check must take into account rounding or truncation.
1910 -- (3) The range of type I may not be exactly representable in F.
1911 -- (4) For the rounding case, the end-points I'First - 0.5 and
1912 -- I'Last + 0.5 may or may not be in range, depending on the
1913 -- sign of I'First and I'Last.
1914 -- (5) X may be a NaN, which will fail any comparison
1916 -- The following steps correctly convert X with rounding:
1918 -- (1) If either I'First or I'Last is not known at compile time, use
1919 -- I'Base instead of I in the next three steps and perform a
1920 -- regular range check against I'Range after conversion.
1921 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1922 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1923 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1924 -- In other words, take one of the closest floating-point numbers
1925 -- (which is an integer value) to I'First, and see if it is in
1927 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1928 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1929 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1930 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1931 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1933 -- For the truncating case, replace steps (2) and (3) as follows:
1934 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1935 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1937 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1938 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1941 procedure Apply_Float_Conversion_Check
1943 Target_Typ
: Entity_Id
)
1945 LB
: constant Node_Id
:= Type_Low_Bound
(Target_Typ
);
1946 HB
: constant Node_Id
:= Type_High_Bound
(Target_Typ
);
1947 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
1948 Expr_Type
: constant Entity_Id
:= Base_Type
(Etype
(Expr
));
1949 Target_Base
: constant Entity_Id
:=
1950 Implementation_Base_Type
(Target_Typ
);
1952 Par
: constant Node_Id
:= Parent
(Expr
);
1953 pragma Assert
(Nkind
(Par
) = N_Type_Conversion
);
1954 -- Parent of check node, must be a type conversion
1956 Truncate
: constant Boolean := Float_Truncate
(Par
);
1957 Max_Bound
: constant Uint
:=
1959 (Machine_Radix_Value
(Expr_Type
),
1960 Machine_Mantissa_Value
(Expr_Type
) - 1) - 1;
1962 -- Largest bound, so bound plus or minus half is a machine number of F
1964 Ifirst
, Ilast
: Uint
;
1965 -- Bounds of integer type
1968 -- Bounds to check in floating-point domain
1970 Lo_OK
, Hi_OK
: Boolean;
1971 -- True iff Lo resp. Hi belongs to I'Range
1973 Lo_Chk
, Hi_Chk
: Node_Id
;
1974 -- Expressions that are False iff check fails
1976 Reason
: RT_Exception_Code
;
1979 -- We do not need checks if we are not generating code (i.e. the full
1980 -- expander is not active). In SPARK mode, we specifically don't want
1981 -- the frontend to expand these checks, which are dealt with directly
1982 -- in the formal verification backend.
1984 if not Expander_Active
then
1988 -- Here we will generate an explicit range check, so we don't want to
1989 -- set the Do_Range check flag, since the range check is taken care of
1990 -- by the code we will generate.
1992 Set_Do_Range_Check
(Expr
, False);
1994 if not Compile_Time_Known_Value
(LB
)
1995 or not Compile_Time_Known_Value
(HB
)
1998 -- First check that the value falls in the range of the base type,
1999 -- to prevent overflow during conversion and then perform a
2000 -- regular range check against the (dynamic) bounds.
2002 pragma Assert
(Target_Base
/= Target_Typ
);
2004 Temp
: constant Entity_Id
:= Make_Temporary
(Loc
, 'T', Par
);
2007 Apply_Float_Conversion_Check
(Expr
, Target_Base
);
2008 Set_Etype
(Temp
, Target_Base
);
2010 -- Note: Previously the declaration was inserted above the parent
2011 -- of the conversion, apparently as a small optimization for the
2012 -- subequent traversal in Insert_Actions. Unfortunately a similar
2013 -- optimization takes place in Insert_Actions, assuming that the
2014 -- insertion point must be above the expression that creates
2015 -- actions. This is not correct in the presence of conditional
2016 -- expressions, where the insertion must be in the list of actions
2017 -- attached to the current alternative.
2020 Make_Object_Declaration
(Loc
,
2021 Defining_Identifier
=> Temp
,
2022 Object_Definition
=> New_Occurrence_Of
(Target_Typ
, Loc
),
2023 Expression
=> New_Copy_Tree
(Par
)),
2024 Suppress
=> All_Checks
);
2027 Make_Raise_Constraint_Error
(Loc
,
2030 Left_Opnd
=> New_Occurrence_Of
(Temp
, Loc
),
2031 Right_Opnd
=> New_Occurrence_Of
(Target_Typ
, Loc
)),
2032 Reason
=> CE_Range_Check_Failed
));
2033 Rewrite
(Par
, New_Occurrence_Of
(Temp
, Loc
));
2039 -- Get the (static) bounds of the target type
2041 Ifirst
:= Expr_Value
(LB
);
2042 Ilast
:= Expr_Value
(HB
);
2044 -- A simple optimization: if the expression is a universal literal,
2045 -- we can do the comparison with the bounds and the conversion to
2046 -- an integer type statically. The range checks are unchanged.
2048 if Nkind
(Expr
) = N_Real_Literal
2049 and then Etype
(Expr
) = Universal_Real
2050 and then Is_Integer_Type
(Target_Typ
)
2053 Int_Val
: constant Uint
:= UR_To_Uint
(Realval
(Expr
));
2056 if Int_Val
<= Ilast
and then Int_Val
>= Ifirst
then
2058 -- Conversion is safe
2060 Rewrite
(Parent
(Expr
),
2061 Make_Integer_Literal
(Loc
, UI_To_Int
(Int_Val
)));
2062 Analyze_And_Resolve
(Parent
(Expr
), Target_Typ
);
2068 -- Check against lower bound
2070 if Truncate
and then Ifirst
> 0 then
2071 Lo
:= Pred
(Expr_Type
, UR_From_Uint
(Ifirst
));
2075 Lo
:= Succ
(Expr_Type
, UR_From_Uint
(Ifirst
- 1));
2078 elsif abs (Ifirst
) < Max_Bound
then
2079 Lo
:= UR_From_Uint
(Ifirst
) - Ureal_Half
;
2080 Lo_OK
:= (Ifirst
> 0);
2083 Lo
:= Machine_Number
(Expr_Type
, UR_From_Uint
(Ifirst
), Expr
);
2084 Lo_OK
:= (Lo
>= UR_From_Uint
(Ifirst
));
2087 -- Saturate the lower bound to that of the expression's type, because
2088 -- we do not want to create an out-of-range value but we still need to
2089 -- do a comparison to catch NaNs.
2091 if Lo
< Expr_Value_R
(Type_Low_Bound
(Expr_Type
)) then
2092 Lo
:= Expr_Value_R
(Type_Low_Bound
(Expr_Type
));
2098 -- Lo_Chk := (X >= Lo)
2100 Lo_Chk
:= Make_Op_Ge
(Loc
,
2101 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Expr
),
2102 Right_Opnd
=> Make_Real_Literal
(Loc
, Lo
));
2105 -- Lo_Chk := (X > Lo)
2107 Lo_Chk
:= Make_Op_Gt
(Loc
,
2108 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Expr
),
2109 Right_Opnd
=> Make_Real_Literal
(Loc
, Lo
));
2112 -- Check against higher bound
2114 if Truncate
and then Ilast
< 0 then
2115 Hi
:= Succ
(Expr_Type
, UR_From_Uint
(Ilast
));
2119 Hi
:= Pred
(Expr_Type
, UR_From_Uint
(Ilast
+ 1));
2122 elsif abs (Ilast
) < Max_Bound
then
2123 Hi
:= UR_From_Uint
(Ilast
) + Ureal_Half
;
2124 Hi_OK
:= (Ilast
< 0);
2126 Hi
:= Machine_Number
(Expr_Type
, UR_From_Uint
(Ilast
), Expr
);
2127 Hi_OK
:= (Hi
<= UR_From_Uint
(Ilast
));
2130 -- Saturate the higher bound to that of the expression's type, because
2131 -- we do not want to create an out-of-range value but we still need to
2132 -- do a comparison to catch NaNs.
2134 if Hi
> Expr_Value_R
(Type_High_Bound
(Expr_Type
)) then
2135 Hi
:= Expr_Value_R
(Type_High_Bound
(Expr_Type
));
2141 -- Hi_Chk := (X <= Hi)
2143 Hi_Chk
:= Make_Op_Le
(Loc
,
2144 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Expr
),
2145 Right_Opnd
=> Make_Real_Literal
(Loc
, Hi
));
2148 -- Hi_Chk := (X < Hi)
2150 Hi_Chk
:= Make_Op_Lt
(Loc
,
2151 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Expr
),
2152 Right_Opnd
=> Make_Real_Literal
(Loc
, Hi
));
2155 -- If the bounds of the target type are the same as those of the base
2156 -- type, the check is an overflow check as a range check is not
2157 -- performed in these cases.
2159 if Expr_Value
(Type_Low_Bound
(Target_Base
)) = Ifirst
2160 and then Expr_Value
(Type_High_Bound
(Target_Base
)) = Ilast
2162 Reason
:= CE_Overflow_Check_Failed
;
2164 Reason
:= CE_Range_Check_Failed
;
2167 -- Raise CE if either conditions does not hold
2169 Insert_Action
(Expr
,
2170 Make_Raise_Constraint_Error
(Loc
,
2171 Condition
=> Make_Op_Not
(Loc
, Make_And_Then
(Loc
, Lo_Chk
, Hi_Chk
)),
2173 end Apply_Float_Conversion_Check
;
2175 ------------------------
2176 -- Apply_Length_Check --
2177 ------------------------
2179 procedure Apply_Length_Check
2181 Target_Typ
: Entity_Id
;
2182 Source_Typ
: Entity_Id
:= Empty
)
2185 Apply_Selected_Length_Checks
2186 (Expr
, Target_Typ
, Source_Typ
, Do_Static
=> False);
2187 end Apply_Length_Check
;
2189 --------------------------------------
2190 -- Apply_Length_Check_On_Assignment --
2191 --------------------------------------
2193 procedure Apply_Length_Check_On_Assignment
2195 Target_Typ
: Entity_Id
;
2197 Source_Typ
: Entity_Id
:= Empty
)
2199 Assign
: constant Node_Id
:= Parent
(Target
);
2202 -- Do not apply length checks if parent is still an assignment statement
2203 -- with Suppress_Assignment_Checks flag set.
2205 if Nkind
(Assign
) = N_Assignment_Statement
2206 and then Suppress_Assignment_Checks
(Assign
)
2211 -- No check is needed for the initialization of an object whose
2212 -- nominal subtype is unconstrained.
2214 if Is_Constr_Subt_For_U_Nominal
(Target_Typ
)
2215 and then Nkind
(Parent
(Assign
)) = N_Freeze_Entity
2216 and then Is_Entity_Name
(Target
)
2217 and then Entity
(Target
) = Entity
(Parent
(Assign
))
2222 Apply_Selected_Length_Checks
2223 (Expr
, Target_Typ
, Source_Typ
, Do_Static
=> False);
2224 end Apply_Length_Check_On_Assignment
;
2226 -------------------------------------
2227 -- Apply_Parameter_Aliasing_Checks --
2228 -------------------------------------
2230 procedure Apply_Parameter_Aliasing_Checks
2234 Loc
: constant Source_Ptr
:= Sloc
(Call
);
2236 function Parameter_Passing_Mechanism_Specified
2239 -- Returns True if parameter-passing mechanism is specified for type Typ
2241 function May_Cause_Aliasing
2242 (Formal_1
: Entity_Id
;
2243 Formal_2
: Entity_Id
) return Boolean;
2244 -- Determine whether two formal parameters can alias each other
2245 -- depending on their modes.
2247 function Original_Actual
(N
: Node_Id
) return Node_Id
;
2248 -- The expander may replace an actual with a temporary for the sake of
2249 -- side effect removal. The temporary may hide a potential aliasing as
2250 -- it does not share the address of the actual. This routine attempts
2251 -- to retrieve the original actual.
2253 procedure Overlap_Check
2254 (Actual_1
: Node_Id
;
2256 Formal_1
: Entity_Id
;
2257 Formal_2
: Entity_Id
;
2258 Check
: in out Node_Id
);
2259 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2260 -- If detailed exception messages are enabled, the check is augmented to
2261 -- provide information about the names of the corresponding formals. See
2262 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2263 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2264 -- Check contains all and-ed simple tests generated so far or remains
2265 -- unchanged in the case of detailed exception messaged.
2267 -------------------------------------------
2268 -- Parameter_Passing_Mechanism_Specified --
2269 -------------------------------------------
2271 function Parameter_Passing_Mechanism_Specified
2276 return Is_Elementary_Type
(Typ
)
2277 or else Is_By_Reference_Type
(Typ
);
2278 end Parameter_Passing_Mechanism_Specified
;
2280 ------------------------
2281 -- May_Cause_Aliasing --
2282 ------------------------
2284 function May_Cause_Aliasing
2285 (Formal_1
: Entity_Id
;
2286 Formal_2
: Entity_Id
) return Boolean
2289 -- The following combination cannot lead to aliasing
2291 -- Formal 1 Formal 2
2294 if Ekind
(Formal_1
) = E_In_Parameter
2296 Ekind
(Formal_2
) = E_In_Parameter
2300 -- The following combinations may lead to aliasing
2302 -- Formal 1 Formal 2
2312 end May_Cause_Aliasing
;
2314 ---------------------
2315 -- Original_Actual --
2316 ---------------------
2318 function Original_Actual
(N
: Node_Id
) return Node_Id
is
2320 if Nkind
(N
) = N_Type_Conversion
then
2321 return Expression
(N
);
2323 -- The expander created a temporary to capture the result of a type
2324 -- conversion where the expression is the real actual.
2326 elsif Nkind
(N
) = N_Identifier
2327 and then Present
(Original_Node
(N
))
2328 and then Nkind
(Original_Node
(N
)) = N_Type_Conversion
2330 return Expression
(Original_Node
(N
));
2334 end Original_Actual
;
2340 procedure Overlap_Check
2341 (Actual_1
: Node_Id
;
2343 Formal_1
: Entity_Id
;
2344 Formal_2
: Entity_Id
;
2345 Check
: in out Node_Id
)
2348 Formal_Name
: Bounded_String
;
2352 -- Actual_1'Overlaps_Storage (Actual_2)
2355 Make_Attribute_Reference
(Loc
,
2356 Prefix
=> New_Copy_Tree
(Original_Actual
(Actual_1
)),
2357 Attribute_Name
=> Name_Overlaps_Storage
,
2359 New_List
(New_Copy_Tree
(Original_Actual
(Actual_2
))));
2361 -- Generate the following check when detailed exception messages are
2364 -- if Actual_1'Overlaps_Storage (Actual_2) then
2365 -- raise Program_Error with <detailed message>;
2368 if Exception_Extra_Info
then
2371 -- Do not generate location information for internal calls
2373 if Comes_From_Source
(Call
) then
2374 Store_String_Chars
(Build_Location_String
(Loc
));
2375 Store_String_Char
(' ');
2378 Store_String_Chars
("aliased parameters, actuals for """);
2380 Append
(Formal_Name
, Chars
(Formal_1
));
2381 Adjust_Name_Case
(Formal_Name
, Sloc
(Formal_1
));
2382 Store_String_Chars
(To_String
(Formal_Name
));
2384 Store_String_Chars
(""" and """);
2386 Formal_Name
.Length
:= 0;
2388 Append
(Formal_Name
, Chars
(Formal_2
));
2389 Adjust_Name_Case
(Formal_Name
, Sloc
(Formal_2
));
2390 Store_String_Chars
(To_String
(Formal_Name
));
2392 Store_String_Chars
(""" overlap");
2394 Insert_Action
(Call
,
2395 Make_If_Statement
(Loc
,
2397 Then_Statements
=> New_List
(
2398 Make_Raise_Statement
(Loc
,
2400 New_Occurrence_Of
(Standard_Program_Error
, Loc
),
2401 Expression
=> Make_String_Literal
(Loc
, End_String
)))));
2403 -- Create a sequence of overlapping checks by and-ing them all
2413 Right_Opnd
=> Cond
);
2423 Formal_1
: Entity_Id
;
2424 Formal_2
: Entity_Id
;
2425 Orig_Act_1
: Node_Id
;
2426 Orig_Act_2
: Node_Id
;
2428 -- Start of processing for Apply_Parameter_Aliasing_Checks
2433 Actual_1
:= First_Actual
(Call
);
2434 Formal_1
:= First_Formal
(Subp
);
2435 while Present
(Actual_1
) and then Present
(Formal_1
) loop
2436 Orig_Act_1
:= Original_Actual
(Actual_1
);
2438 if Is_Name_Reference
(Orig_Act_1
) then
2439 Actual_2
:= Next_Actual
(Actual_1
);
2440 Formal_2
:= Next_Formal
(Formal_1
);
2441 while Present
(Actual_2
) and then Present
(Formal_2
) loop
2442 Orig_Act_2
:= Original_Actual
(Actual_2
);
2444 -- Generate the check only when the mode of the two formals may
2445 -- lead to aliasing.
2447 if Is_Name_Reference
(Orig_Act_2
)
2448 and then May_Cause_Aliasing
(Formal_1
, Formal_2
)
2451 -- The aliasing check only applies when some of the formals
2452 -- have their passing mechanism unspecified; RM 6.2 (12/3).
2454 if Parameter_Passing_Mechanism_Specified
(Etype
(Orig_Act_1
))
2456 Parameter_Passing_Mechanism_Specified
(Etype
(Orig_Act_2
))
2460 Remove_Side_Effects
(Actual_1
);
2461 Remove_Side_Effects
(Actual_2
);
2464 (Actual_1
=> Actual_1
,
2465 Actual_2
=> Actual_2
,
2466 Formal_1
=> Formal_1
,
2467 Formal_2
=> Formal_2
,
2472 Next_Actual
(Actual_2
);
2473 Next_Formal
(Formal_2
);
2477 Next_Actual
(Actual_1
);
2478 Next_Formal
(Formal_1
);
2481 -- Place a simple check right before the call
2483 if Present
(Check
) and then not Exception_Extra_Info
then
2484 Insert_Action
(Call
,
2485 Make_Raise_Program_Error
(Loc
,
2487 Reason
=> PE_Aliased_Parameters
));
2489 end Apply_Parameter_Aliasing_Checks
;
2491 -------------------------------------
2492 -- Apply_Parameter_Validity_Checks --
2493 -------------------------------------
2495 procedure Apply_Parameter_Validity_Checks
(Subp
: Entity_Id
) is
2496 Subp_Decl
: Node_Id
;
2498 procedure Add_Validity_Check
2499 (Formal
: Entity_Id
;
2501 For_Result
: Boolean := False);
2502 -- Add a single 'Valid[_Scalars] check which verifies the initialization
2503 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
2504 -- Set flag For_Result when to verify the result of a function.
2506 ------------------------
2507 -- Add_Validity_Check --
2508 ------------------------
2510 procedure Add_Validity_Check
2511 (Formal
: Entity_Id
;
2513 For_Result
: Boolean := False)
2515 procedure Build_Pre_Post_Condition
(Expr
: Node_Id
);
2516 -- Create a pre/postcondition pragma that tests expression Expr
2518 ------------------------------
2519 -- Build_Pre_Post_Condition --
2520 ------------------------------
2522 procedure Build_Pre_Post_Condition
(Expr
: Node_Id
) is
2523 Loc
: constant Source_Ptr
:= Sloc
(Subp
);
2531 Pragma_Argument_Associations
=> New_List
(
2532 Make_Pragma_Argument_Association
(Loc
,
2533 Chars
=> Name_Check
,
2534 Expression
=> Expr
)));
2536 -- Add a message unless exception messages are suppressed
2538 if not Exception_Locations_Suppressed
then
2539 Append_To
(Pragma_Argument_Associations
(Prag
),
2540 Make_Pragma_Argument_Association
(Loc
,
2541 Chars
=> Name_Message
,
2543 Make_String_Literal
(Loc
,
2545 & Get_Name_String
(Prag_Nam
)
2547 & Build_Location_String
(Loc
))));
2550 -- Insert the pragma in the tree
2552 if Nkind
(Parent
(Subp_Decl
)) = N_Compilation_Unit
then
2553 Add_Global_Declaration
(Prag
);
2556 -- PPC pragmas associated with subprogram bodies must be inserted
2557 -- in the declarative part of the body.
2559 elsif Nkind
(Subp_Decl
) = N_Subprogram_Body
then
2560 Decls
:= Declarations
(Subp_Decl
);
2564 Set_Declarations
(Subp_Decl
, Decls
);
2567 Prepend_To
(Decls
, Prag
);
2570 -- For subprogram declarations insert the PPC pragma right after
2571 -- the declarative node.
2574 Insert_After_And_Analyze
(Subp_Decl
, Prag
);
2576 end Build_Pre_Post_Condition
;
2580 Loc
: constant Source_Ptr
:= Sloc
(Subp
);
2581 Typ
: constant Entity_Id
:= Etype
(Formal
);
2585 -- Start of processing for Add_Validity_Check
2588 -- For scalars, generate 'Valid test
2590 if Is_Scalar_Type
(Typ
) then
2593 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2595 elsif Scalar_Part_Present
(Typ
) then
2596 Nam
:= Name_Valid_Scalars
;
2598 -- No test needed for other cases (no scalars to test)
2604 -- Step 1: Create the expression to verify the validity of the
2607 Check
:= New_Occurrence_Of
(Formal
, Loc
);
2609 -- When processing a function result, use 'Result. Generate
2614 Make_Attribute_Reference
(Loc
,
2616 Attribute_Name
=> Name_Result
);
2620 -- Context['Result]'Valid[_Scalars]
2623 Make_Attribute_Reference
(Loc
,
2625 Attribute_Name
=> Nam
);
2627 -- Step 2: Create a pre or post condition pragma
2629 Build_Pre_Post_Condition
(Check
);
2630 end Add_Validity_Check
;
2635 Subp_Spec
: Node_Id
;
2637 -- Start of processing for Apply_Parameter_Validity_Checks
2640 -- Extract the subprogram specification and declaration nodes
2642 Subp_Spec
:= Parent
(Subp
);
2644 if No
(Subp_Spec
) then
2648 if Nkind
(Subp_Spec
) = N_Defining_Program_Unit_Name
then
2649 Subp_Spec
:= Parent
(Subp_Spec
);
2652 Subp_Decl
:= Parent
(Subp_Spec
);
2654 if not Comes_From_Source
(Subp
)
2656 -- Do not process formal subprograms because the corresponding actual
2657 -- will receive the proper checks when the instance is analyzed.
2659 or else Is_Formal_Subprogram
(Subp
)
2661 -- Do not process imported subprograms since pre and postconditions
2662 -- are never verified on routines coming from a different language.
2664 or else Is_Imported
(Subp
)
2665 or else Is_Intrinsic_Subprogram
(Subp
)
2667 -- The PPC pragmas generated by this routine do not correspond to
2668 -- source aspects, therefore they cannot be applied to abstract
2671 or else Nkind
(Subp_Decl
) = N_Abstract_Subprogram_Declaration
2673 -- Do not consider subprogram renaminds because the renamed entity
2674 -- already has the proper PPC pragmas.
2676 or else Nkind
(Subp_Decl
) = N_Subprogram_Renaming_Declaration
2678 -- Do not process null procedures because there is no benefit of
2679 -- adding the checks to a no action routine.
2681 or else (Nkind
(Subp_Spec
) = N_Procedure_Specification
2682 and then Null_Present
(Subp_Spec
))
2687 -- Inspect all the formals applying aliasing and scalar initialization
2688 -- checks where applicable.
2690 Formal
:= First_Formal
(Subp
);
2691 while Present
(Formal
) loop
2693 -- Generate the following scalar initialization checks for each
2694 -- formal parameter:
2696 -- mode IN - Pre => Formal'Valid[_Scalars]
2697 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2698 -- mode OUT - Post => Formal'Valid[_Scalars]
2700 if Ekind
(Formal
) in E_In_Parameter | E_In_Out_Parameter
then
2701 Add_Validity_Check
(Formal
, Name_Precondition
, False);
2704 if Ekind
(Formal
) in E_In_Out_Parameter | E_Out_Parameter
then
2705 Add_Validity_Check
(Formal
, Name_Postcondition
, False);
2708 Next_Formal
(Formal
);
2711 -- Generate following scalar initialization check for function result:
2713 -- Post => Subp'Result'Valid[_Scalars]
2715 if Ekind
(Subp
) = E_Function
then
2716 Add_Validity_Check
(Subp
, Name_Postcondition
, True);
2718 end Apply_Parameter_Validity_Checks
;
2720 ---------------------------
2721 -- Apply_Predicate_Check --
2722 ---------------------------
2724 procedure Apply_Predicate_Check
2727 Deref
: Boolean := False;
2728 Fun
: Entity_Id
:= Empty
)
2730 Loc
: constant Source_Ptr
:= Sloc
(N
);
2731 Check_Disabled
: constant Boolean :=
2732 not Predicate_Enabled
(Typ
)
2733 or else not Predicate_Check_In_Scope
(N
);
2741 while Present
(S
) and then not Is_Subprogram
(S
) loop
2745 -- If the check appears within the predicate function itself, it means
2746 -- that the user specified a check whose formal is the predicated
2747 -- subtype itself, rather than some covering type. This is likely to be
2748 -- a common error, and thus deserves a warning. We want to emit this
2749 -- warning even if predicate checking is disabled (in which case the
2750 -- warning is still useful even if it is not strictly accurate).
2752 if Present
(S
) and then S
= Predicate_Function
(Typ
) then
2754 ("predicate check includes a call to& that requires a "
2755 & "predicate check??", Parent
(N
), Fun
);
2757 ("\this will result in infinite recursion??", Parent
(N
));
2759 if Is_First_Subtype
(Typ
) then
2761 ("\use an explicit subtype of& to carry the predicate",
2765 if not Check_Disabled
then
2767 Make_Raise_Storage_Error
(Loc
,
2768 Reason
=> SE_Infinite_Recursion
));
2773 if Check_Disabled
then
2777 -- Normal case of predicate active
2779 -- If the expression is an IN parameter, the predicate will have
2780 -- been applied at the point of call. An additional check would
2781 -- be redundant, or will lead to out-of-scope references if the
2782 -- call appears within an aspect specification for a precondition.
2784 -- However, if the reference is within the body of the subprogram
2785 -- that declares the formal, the predicate can safely be applied,
2786 -- which may be necessary for a nested call whose formal has a
2787 -- different predicate.
2789 if Is_Entity_Name
(N
)
2790 and then Ekind
(Entity
(N
)) = E_In_Parameter
2793 In_Body
: Boolean := False;
2794 P
: Node_Id
:= Parent
(N
);
2797 while Present
(P
) loop
2798 if Nkind
(P
) = N_Subprogram_Body
2800 ((Present
(Corresponding_Spec
(P
))
2802 Corresponding_Spec
(P
) = Scope
(Entity
(N
)))
2804 Defining_Unit_Name
(Specification
(P
)) =
2820 -- If the type has a static predicate and the expression is known
2821 -- at compile time, see if the expression satisfies the predicate.
2823 Check_Expression_Against_Static_Predicate
(N
, Typ
);
2825 if not Expander_Active
then
2830 if Nkind
(Par
) = N_Qualified_Expression
then
2831 Par
:= Parent
(Par
);
2834 -- Try to avoid creating a temporary if the expression is an aggregate
2836 if Nkind
(N
) in N_Aggregate | N_Extension_Aggregate
then
2838 -- If the expression is an aggregate in an assignment, apply the
2839 -- check to the LHS after the assignment, rather than create a
2840 -- redundant temporary. This is only necessary in rare cases
2841 -- of array types (including strings) initialized with an
2842 -- aggregate with an "others" clause, either coming from source
2843 -- or generated by an Initialize_Scalars pragma.
2845 if Nkind
(Par
) = N_Assignment_Statement
then
2846 Insert_Action_After
(Par
,
2847 Make_Predicate_Check
2848 (Typ
, Duplicate_Subexpr
(Name
(Par
))));
2851 -- Similarly, if the expression is an aggregate in an object
2852 -- declaration, apply it to the object after the declaration.
2854 -- This is only necessary in cases of tagged extensions
2855 -- initialized with an aggregate with an "others => <>" clause,
2856 -- when the subtypes of LHS and RHS do not statically match or
2857 -- when we know the object's type will be rewritten later.
2858 -- The condition for the later is copied from the
2859 -- Analyze_Object_Declaration procedure when it actually builds the
2862 elsif Nkind
(Par
) = N_Object_Declaration
then
2863 if Subtypes_Statically_Match
2864 (Etype
(Defining_Identifier
(Par
)), Typ
)
2865 and then (Nkind
(N
) = N_Extension_Aggregate
2866 or else (Is_Definite_Subtype
(Typ
)
2867 and then Build_Default_Subtype_OK
(Typ
)))
2869 Insert_Action_After
(Par
,
2870 Make_Predicate_Check
(Typ
,
2871 New_Occurrence_Of
(Defining_Identifier
(Par
), Loc
)));
2878 -- For an entity of the type, generate a call to the predicate
2879 -- function, unless its type is an actual subtype, which is not
2880 -- visible outside of the enclosing subprogram.
2882 if Is_Entity_Name
(N
) and then not Is_Actual_Subtype
(Typ
) then
2883 Expr
:= New_Occurrence_Of
(Entity
(N
), Loc
);
2885 -- If the expression is not an entity, it may have side effects
2888 Expr
:= Duplicate_Subexpr
(N
);
2891 -- Make the dereference if requested
2894 Expr
:= Make_Explicit_Dereference
(Loc
, Prefix
=> Expr
);
2897 -- Disable checks to prevent an infinite recursion
2900 (N
, Make_Predicate_Check
(Typ
, Expr
), Suppress
=> All_Checks
);
2901 end Apply_Predicate_Check
;
2903 -----------------------
2904 -- Apply_Range_Check --
2905 -----------------------
2907 procedure Apply_Range_Check
2909 Target_Typ
: Entity_Id
;
2910 Source_Typ
: Entity_Id
:= Empty
;
2911 Insert_Node
: Node_Id
:= Empty
)
2913 Checks_On
: constant Boolean :=
2914 not Index_Checks_Suppressed
(Target_Typ
)
2916 not Range_Checks_Suppressed
(Target_Typ
);
2918 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
2922 R_Result
: Check_Result
;
2925 -- Only apply checks when generating code. In GNATprove mode, we do not
2926 -- apply the checks, but we still call Selected_Range_Checks to possibly
2927 -- issue errors on SPARK code when a run-time error can be detected at
2930 if not GNATprove_Mode
then
2931 if not Expander_Active
or not Checks_On
then
2937 Selected_Range_Checks
(Expr
, Target_Typ
, Source_Typ
, Insert_Node
);
2939 if GNATprove_Mode
then
2943 for J
in 1 .. 2 loop
2944 R_Cno
:= R_Result
(J
);
2945 exit when No
(R_Cno
);
2947 -- The range check requires runtime evaluation. Depending on what its
2948 -- triggering condition is, the check may be converted into a compile
2949 -- time constraint check.
2951 if Nkind
(R_Cno
) = N_Raise_Constraint_Error
2952 and then Present
(Condition
(R_Cno
))
2954 Cond
:= Condition
(R_Cno
);
2956 -- Insert the range check before the related context. Note that
2957 -- this action analyses the triggering condition.
2959 if Present
(Insert_Node
) then
2960 Insert_Action
(Insert_Node
, R_Cno
);
2962 Insert_Action
(Expr
, R_Cno
);
2965 -- The triggering condition evaluates to True, the range check
2966 -- can be converted into a compile time constraint check.
2968 if Is_Entity_Name
(Cond
)
2969 and then Entity
(Cond
) = Standard_True
2971 -- Since an N_Range is technically not an expression, we have
2972 -- to set one of the bounds to C_E and then just flag the
2973 -- N_Range. The warning message will point to the lower bound
2974 -- and complain about a range, which seems OK.
2976 if Nkind
(Expr
) = N_Range
then
2977 Apply_Compile_Time_Constraint_Error
2979 "static range out of bounds of}??",
2980 CE_Range_Check_Failed
,
2984 Set_Raises_Constraint_Error
(Expr
);
2987 Apply_Compile_Time_Constraint_Error
2989 "static value out of range of}??",
2990 CE_Range_Check_Failed
,
2996 -- The range check raises Constraint_Error explicitly
2998 elsif Present
(Insert_Node
) then
3000 Make_Raise_Constraint_Error
(Sloc
(Insert_Node
),
3001 Reason
=> CE_Range_Check_Failed
);
3003 Insert_Action
(Insert_Node
, R_Cno
);
3006 Install_Static_Check
(R_Cno
, Loc
, CE_Range_Check_Failed
);
3009 end Apply_Range_Check
;
3011 ------------------------------
3012 -- Apply_Scalar_Range_Check --
3013 ------------------------------
3015 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
3016 -- off if it is already set on.
3018 procedure Apply_Scalar_Range_Check
3020 Target_Typ
: Entity_Id
;
3021 Source_Typ
: Entity_Id
:= Empty
;
3022 Fixed_Int
: Boolean := False)
3024 Parnt
: constant Node_Id
:= Parent
(Expr
);
3026 Arr
: Node_Id
:= Empty
; -- initialize to prevent warning
3027 Arr_Typ
: Entity_Id
:= Empty
; -- initialize to prevent warning
3029 Is_Subscr_Ref
: Boolean;
3030 -- Set true if Expr is a subscript
3032 Is_Unconstrained_Subscr_Ref
: Boolean;
3033 -- Set true if Expr is a subscript of an unconstrained array. In this
3034 -- case we do not attempt to do an analysis of the value against the
3035 -- range of the subscript, since we don't know the actual subtype.
3038 -- Set to True if Expr should be regarded as a real value even though
3039 -- the type of Expr might be discrete.
3041 procedure Bad_Value
(Warn
: Boolean := False);
3042 -- Procedure called if value is determined to be out of range. Warn is
3043 -- True to force a warning instead of an error, even when SPARK_Mode is
3050 procedure Bad_Value
(Warn
: Boolean := False) is
3052 Apply_Compile_Time_Constraint_Error
3053 (Expr
, "value not in range of}??", CE_Range_Check_Failed
,
3059 -- Start of processing for Apply_Scalar_Range_Check
3062 -- Return if check obviously not needed
3065 -- Not needed inside generic
3069 -- Not needed if previous error
3071 or else Target_Typ
= Any_Type
3072 or else Nkind
(Expr
) = N_Error
3074 -- Not needed for non-scalar type
3076 or else not Is_Scalar_Type
(Target_Typ
)
3078 -- Not needed if we know node raises CE already
3080 or else Raises_Constraint_Error
(Expr
)
3085 -- Now, see if checks are suppressed
3088 Is_List_Member
(Expr
) and then Nkind
(Parnt
) = N_Indexed_Component
;
3090 if Is_Subscr_Ref
then
3091 Arr
:= Prefix
(Parnt
);
3092 Arr_Typ
:= Get_Actual_Subtype_If_Available
(Arr
);
3094 if Is_Access_Type
(Arr_Typ
) then
3095 Arr_Typ
:= Designated_Type
(Arr_Typ
);
3099 if not Do_Range_Check
(Expr
) then
3101 -- Subscript reference. Check for Index_Checks suppressed
3103 if Is_Subscr_Ref
then
3105 -- Check array type and its base type
3107 if Index_Checks_Suppressed
(Arr_Typ
)
3108 or else Index_Checks_Suppressed
(Base_Type
(Arr_Typ
))
3112 -- Check array itself if it is an entity name
3114 elsif Is_Entity_Name
(Arr
)
3115 and then Index_Checks_Suppressed
(Entity
(Arr
))
3119 -- Check expression itself if it is an entity name
3121 elsif Is_Entity_Name
(Expr
)
3122 and then Index_Checks_Suppressed
(Entity
(Expr
))
3127 -- All other cases, check for Range_Checks suppressed
3130 -- Check target type and its base type
3132 if Range_Checks_Suppressed
(Target_Typ
)
3133 or else Range_Checks_Suppressed
(Base_Type
(Target_Typ
))
3137 -- Check expression itself if it is an entity name
3139 elsif Is_Entity_Name
(Expr
)
3140 and then Range_Checks_Suppressed
(Entity
(Expr
))
3144 -- If Expr is part of an assignment statement, then check left
3145 -- side of assignment if it is an entity name.
3147 elsif Nkind
(Parnt
) = N_Assignment_Statement
3148 and then Is_Entity_Name
(Name
(Parnt
))
3149 and then Range_Checks_Suppressed
(Entity
(Name
(Parnt
)))
3156 -- Do not set range checks if they are killed
3158 if Nkind
(Expr
) = N_Unchecked_Type_Conversion
3159 and then Kill_Range_Check
(Expr
)
3164 -- Do not set range checks for any values from System.Scalar_Values
3165 -- since the whole idea of such values is to avoid checking them.
3167 if Is_Entity_Name
(Expr
)
3168 and then Is_RTU
(Scope
(Entity
(Expr
)), System_Scalar_Values
)
3173 -- Now see if we need a check
3175 if No
(Source_Typ
) then
3176 S_Typ
:= Etype
(Expr
);
3178 S_Typ
:= Source_Typ
;
3181 if not Is_Scalar_Type
(S_Typ
) or else S_Typ
= Any_Type
then
3185 Is_Unconstrained_Subscr_Ref
:=
3186 Is_Subscr_Ref
and then not Is_Constrained
(Arr_Typ
);
3188 -- Special checks for floating-point type
3190 if Is_Floating_Point_Type
(S_Typ
) then
3192 -- Always do a range check if the source type includes infinities and
3193 -- the target type does not include infinities. We do not do this if
3194 -- range checks are killed.
3195 -- If the expression is a literal and the bounds of the type are
3196 -- static constants it may be possible to optimize the check.
3198 if Has_Infinities
(S_Typ
)
3199 and then not Has_Infinities
(Target_Typ
)
3201 -- If the expression is a literal and the bounds of the type are
3202 -- static constants it may be possible to optimize the check.
3204 if Nkind
(Expr
) = N_Real_Literal
then
3206 Tlo
: constant Node_Id
:= Type_Low_Bound
(Target_Typ
);
3207 Thi
: constant Node_Id
:= Type_High_Bound
(Target_Typ
);
3210 if Compile_Time_Known_Value
(Tlo
)
3211 and then Compile_Time_Known_Value
(Thi
)
3212 and then Expr_Value_R
(Expr
) >= Expr_Value_R
(Tlo
)
3213 and then Expr_Value_R
(Expr
) <= Expr_Value_R
(Thi
)
3217 Enable_Range_Check
(Expr
);
3222 Enable_Range_Check
(Expr
);
3227 -- Return if we know expression is definitely in the range of the target
3228 -- type as determined by Determine_Range_To_Discrete. Right now we only
3229 -- do this for discrete target types, i.e. neither for fixed-point nor
3230 -- for floating-point types. But the additional less precise tests below
3231 -- catch these cases.
3233 -- Note: skip this if we are given a source_typ, since the point of
3234 -- supplying a Source_Typ is to stop us looking at the expression.
3235 -- We could sharpen this test to be out parameters only ???
3237 if Is_Discrete_Type
(Target_Typ
)
3238 and then not Is_Unconstrained_Subscr_Ref
3239 and then No
(Source_Typ
)
3242 Thi
: constant Node_Id
:= Type_High_Bound
(Target_Typ
);
3243 Tlo
: constant Node_Id
:= Type_Low_Bound
(Target_Typ
);
3246 if Compile_Time_Known_Value
(Tlo
)
3247 and then Compile_Time_Known_Value
(Thi
)
3250 OK
: Boolean := False; -- initialize to prevent warning
3251 Hiv
: constant Uint
:= Expr_Value
(Thi
);
3252 Lov
: constant Uint
:= Expr_Value
(Tlo
);
3253 Hi
: Uint
:= No_Uint
;
3254 Lo
: Uint
:= No_Uint
;
3257 -- If range is null, we for sure have a constraint error (we
3258 -- don't even need to look at the value involved, since all
3259 -- possible values will raise CE).
3263 -- When SPARK_Mode is On, force a warning instead of
3264 -- an error in that case, as this likely corresponds
3265 -- to deactivated code.
3267 Bad_Value
(Warn
=> SPARK_Mode
= On
);
3272 -- Otherwise determine range of value
3274 Determine_Range_To_Discrete
3275 (Expr
, OK
, Lo
, Hi
, Fixed_Int
, Assume_Valid
=> True);
3279 -- If definitely in range, all OK
3281 if Lo
>= Lov
and then Hi
<= Hiv
then
3284 -- If definitely not in range, warn
3286 elsif Lov
> Hi
or else Hiv
< Lo
then
3288 -- Ignore out of range values for System.Priority in
3289 -- CodePeer mode since the actual target compiler may
3290 -- provide a wider range.
3292 if not CodePeer_Mode
3293 or else not Is_RTE
(Target_Typ
, RE_Priority
)
3300 -- Otherwise we don't know
3312 Is_Floating_Point_Type
(S_Typ
)
3313 or else (Is_Fixed_Point_Type
(S_Typ
) and then not Fixed_Int
);
3315 -- Check if we can determine at compile time whether Expr is in the
3316 -- range of the target type. Note that if S_Typ is within the bounds
3317 -- of Target_Typ then this must be the case. This check is meaningful
3318 -- only if this is not a conversion between integer and real types,
3319 -- unless for a fixed-point type if Fixed_Int is set.
3321 if not Is_Unconstrained_Subscr_Ref
3322 and then (Is_Discrete_Type
(S_Typ
) = Is_Discrete_Type
(Target_Typ
)
3323 or else (Fixed_Int
and then Is_Discrete_Type
(Target_Typ
)))
3325 (In_Subrange_Of
(S_Typ
, Target_Typ
, Fixed_Int
)
3327 -- Also check if the expression itself is in the range of the
3328 -- target type if it is a known at compile time value. We skip
3329 -- this test if S_Typ is set since for OUT and IN OUT parameters
3330 -- the Expr itself is not relevant to the checking.
3334 and then Is_In_Range
(Expr
, Target_Typ
,
3335 Assume_Valid
=> True,
3336 Fixed_Int
=> Fixed_Int
,
3337 Int_Real
=> Int_Real
)))
3341 elsif Is_Out_Of_Range
(Expr
, Target_Typ
,
3342 Assume_Valid
=> True,
3343 Fixed_Int
=> Fixed_Int
,
3344 Int_Real
=> Int_Real
)
3349 -- Floating-point case
3350 -- In the floating-point case, we only do range checks if the type is
3351 -- constrained. We definitely do NOT want range checks for unconstrained
3352 -- types, since we want to have infinities, except when
3353 -- Check_Float_Overflow is set.
3355 elsif Is_Floating_Point_Type
(S_Typ
) then
3356 if Is_Constrained
(S_Typ
) or else Check_Float_Overflow
then
3357 Enable_Range_Check
(Expr
);
3360 -- For all other cases we enable a range check unconditionally
3363 Enable_Range_Check
(Expr
);
3366 end Apply_Scalar_Range_Check
;
3368 ----------------------------------
3369 -- Apply_Selected_Length_Checks --
3370 ----------------------------------
3372 procedure Apply_Selected_Length_Checks
3374 Target_Typ
: Entity_Id
;
3375 Source_Typ
: Entity_Id
;
3376 Do_Static
: Boolean)
3378 Checks_On
: constant Boolean :=
3379 not Index_Checks_Suppressed
(Target_Typ
)
3381 not Length_Checks_Suppressed
(Target_Typ
);
3383 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
3387 R_Result
: Check_Result
;
3390 -- Only apply checks when generating code
3392 -- Note: this means that we lose some useful warnings if the expander
3395 if not Expander_Active
then
3400 Selected_Length_Checks
(Expr
, Target_Typ
, Source_Typ
, Empty
);
3402 for J
in 1 .. 2 loop
3403 R_Cno
:= R_Result
(J
);
3404 exit when No
(R_Cno
);
3406 -- A length check may mention an Itype which is attached to a
3407 -- subsequent node. At the top level in a package this can cause
3408 -- an order-of-elaboration problem, so we make sure that the itype
3409 -- is referenced now.
3411 if Ekind
(Current_Scope
) = E_Package
3412 and then Is_Compilation_Unit
(Current_Scope
)
3414 Ensure_Defined
(Target_Typ
, Expr
);
3416 if Present
(Source_Typ
) then
3417 Ensure_Defined
(Source_Typ
, Expr
);
3419 elsif Is_Itype
(Etype
(Expr
)) then
3420 Ensure_Defined
(Etype
(Expr
), Expr
);
3424 if Nkind
(R_Cno
) = N_Raise_Constraint_Error
3425 and then Present
(Condition
(R_Cno
))
3427 Cond
:= Condition
(R_Cno
);
3429 -- Case where node does not now have a dynamic check
3431 if not Has_Dynamic_Length_Check
(Expr
) then
3433 -- If checks are on, just insert the check
3436 Insert_Action
(Expr
, R_Cno
);
3438 if not Do_Static
then
3439 Set_Has_Dynamic_Length_Check
(Expr
);
3442 -- If checks are off, then analyze the length check after
3443 -- temporarily attaching it to the tree in case the relevant
3444 -- condition can be evaluated at compile time. We still want a
3445 -- compile time warning in this case.
3448 Set_Parent
(R_Cno
, Expr
);
3453 -- Output a warning if the condition is known to be True
3455 if Is_Entity_Name
(Cond
)
3456 and then Entity
(Cond
) = Standard_True
3458 Apply_Compile_Time_Constraint_Error
3459 (Expr
, "wrong length for array of}??",
3460 CE_Length_Check_Failed
,
3464 -- If we were only doing a static check, or if checks are not
3465 -- on, then we want to delete the check, since it is not needed.
3466 -- We do this by replacing the if statement by a null statement
3468 elsif Do_Static
or else not Checks_On
then
3469 Remove_Warning_Messages
(R_Cno
);
3470 Rewrite
(R_Cno
, Make_Null_Statement
(Loc
));
3474 Install_Static_Check
(R_Cno
, Loc
, CE_Length_Check_Failed
);
3477 end Apply_Selected_Length_Checks
;
3479 -------------------------------
3480 -- Apply_Static_Length_Check --
3481 -------------------------------
3483 procedure Apply_Static_Length_Check
3485 Target_Typ
: Entity_Id
;
3486 Source_Typ
: Entity_Id
:= Empty
)
3489 Apply_Selected_Length_Checks
3490 (Expr
, Target_Typ
, Source_Typ
, Do_Static
=> True);
3491 end Apply_Static_Length_Check
;
3493 -------------------------------------
3494 -- Apply_Subscript_Validity_Checks --
3495 -------------------------------------
3497 procedure Apply_Subscript_Validity_Checks
3499 No_Check_Needed
: Dimension_Set
:= Empty_Dimension_Set
) is
3502 Dimension
: Pos
:= 1;
3504 pragma Assert
(Nkind
(Expr
) = N_Indexed_Component
);
3506 -- Loop through subscripts
3508 Sub
:= First
(Expressions
(Expr
));
3509 while Present
(Sub
) loop
3511 -- Check one subscript. Note that we do not worry about enumeration
3512 -- type with holes, since we will convert the value to a Pos value
3513 -- for the subscript, and that convert will do the necessary validity
3516 if No_Check_Needed
= Empty_Dimension_Set
3517 or else not No_Check_Needed
.Elements
(Dimension
)
3519 Ensure_Valid
(Sub
, Holes_OK
=> True);
3522 -- Move to next subscript
3525 Dimension
:= Dimension
+ 1;
3527 end Apply_Subscript_Validity_Checks
;
3529 ----------------------------------
3530 -- Apply_Type_Conversion_Checks --
3531 ----------------------------------
3533 procedure Apply_Type_Conversion_Checks
(N
: Node_Id
) is
3534 Target_Type
: constant Entity_Id
:= Etype
(N
);
3535 Target_Base
: constant Entity_Id
:= Base_Type
(Target_Type
);
3536 Expr
: constant Node_Id
:= Expression
(N
);
3538 Expr_Type
: constant Entity_Id
:= Underlying_Type
(Etype
(Expr
));
3539 -- Note: if Etype (Expr) is a private type without discriminants, its
3540 -- full view might have discriminants with defaults, so we need the
3541 -- full view here to retrieve the constraints.
3543 procedure Make_Discriminant_Constraint_Check
3544 (Target_Type
: Entity_Id
;
3545 Expr_Type
: Entity_Id
);
3546 -- Generate a discriminant check based on the target type and expression
3549 ----------------------------------------
3550 -- Make_Discriminant_Constraint_Check --
3551 ----------------------------------------
3553 procedure Make_Discriminant_Constraint_Check
3554 (Target_Type
: Entity_Id
;
3555 Expr_Type
: Entity_Id
)
3557 Loc
: constant Source_Ptr
:= Sloc
(N
);
3559 Constraint
: Elmt_Id
;
3560 Discr_Value
: Node_Id
;
3563 New_Constraints
: constant Elist_Id
:= New_Elmt_List
;
3564 Old_Constraints
: constant Elist_Id
:=
3565 Discriminant_Constraint
(Expr_Type
);
3568 -- Build an actual discriminant constraint list using the stored
3569 -- constraint, to verify that the expression of the parent type
3570 -- satisfies the constraints imposed by the (unconstrained) derived
3571 -- type. This applies to value conversions, not to view conversions
3574 Constraint
:= First_Elmt
(Stored_Constraint
(Target_Type
));
3575 while Present
(Constraint
) loop
3576 Discr_Value
:= Node
(Constraint
);
3578 if Is_Entity_Name
(Discr_Value
)
3579 and then Ekind
(Entity
(Discr_Value
)) = E_Discriminant
3581 Discr
:= Corresponding_Discriminant
(Entity
(Discr_Value
));
3584 and then Scope
(Discr
) = Base_Type
(Expr_Type
)
3586 -- Parent is constrained by new discriminant. Obtain
3587 -- Value of original discriminant in expression. If the
3588 -- new discriminant has been used to constrain more than
3589 -- one of the stored discriminants, this will provide the
3590 -- required consistency check.
3593 (Make_Selected_Component
(Loc
,
3595 Duplicate_Subexpr_No_Checks
3596 (Expr
, Name_Req
=> True),
3598 Make_Identifier
(Loc
, Chars
(Discr
))),
3602 -- Discriminant of more remote ancestor ???
3607 -- Derived type definition has an explicit value for this
3608 -- stored discriminant.
3612 (Duplicate_Subexpr_No_Checks
(Discr_Value
),
3616 Next_Elmt
(Constraint
);
3619 -- Use the unconstrained expression type to retrieve the
3620 -- discriminants of the parent, and apply momentarily the
3621 -- discriminant constraint synthesized above.
3623 -- Note: We use Expr_Type instead of Target_Type since the number of
3624 -- actual discriminants may be different due to the presence of
3625 -- stored discriminants and cause Build_Discriminant_Checks to fail.
3627 Set_Discriminant_Constraint
(Expr_Type
, New_Constraints
);
3628 Cond
:= Build_Discriminant_Checks
(Expr
, Expr_Type
);
3629 Set_Discriminant_Constraint
(Expr_Type
, Old_Constraints
);
3631 -- Conversion between access types requires that we check for null
3632 -- before checking discriminants.
3634 if Is_Access_Type
(Etype
(Expr
)) then
3635 Cond
:= Make_And_Then
(Loc
,
3639 Duplicate_Subexpr_No_Checks
3640 (Expr
, Name_Req
=> True),
3641 Right_Opnd
=> Make_Null
(Loc
)),
3642 Right_Opnd
=> Cond
);
3646 Make_Raise_Constraint_Error
(Loc
,
3648 Reason
=> CE_Discriminant_Check_Failed
));
3649 end Make_Discriminant_Constraint_Check
;
3651 -- Start of processing for Apply_Type_Conversion_Checks
3654 if Inside_A_Generic
then
3657 -- Skip these checks if serious errors detected, there are some nasty
3658 -- situations of incomplete trees that blow things up.
3660 elsif Serious_Errors_Detected
> 0 then
3663 -- Never generate discriminant checks for Unchecked_Union types
3665 elsif Present
(Expr_Type
)
3666 and then Is_Unchecked_Union
(Expr_Type
)
3670 -- Scalar type conversions of the form Target_Type (Expr) require a
3671 -- range check if we cannot be sure that Expr is in the base type of
3672 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3673 -- are not quite the same condition from an implementation point of
3674 -- view, but clearly the second includes the first.
3676 elsif Is_Scalar_Type
(Target_Type
) then
3678 Conv_OK
: constant Boolean := Conversion_OK
(N
);
3679 -- If the Conversion_OK flag on the type conversion is set and no
3680 -- floating-point type is involved in the type conversion then
3681 -- fixed-point values must be read as integral values.
3683 Float_To_Int
: constant Boolean :=
3684 Is_Floating_Point_Type
(Expr_Type
)
3685 and then Is_Integer_Type
(Target_Type
);
3688 if not Overflow_Checks_Suppressed
(Target_Base
)
3689 and then not Overflow_Checks_Suppressed
(Target_Type
)
3691 In_Subrange_Of
(Expr_Type
, Target_Base
, Fixed_Int
=> Conv_OK
)
3692 and then not Float_To_Int
3694 -- A small optimization: the attribute 'Pos applied to an
3695 -- enumeration type has a known range, even though its type is
3696 -- Universal_Integer. So in numeric conversions it is usually
3697 -- within range of the target integer type. Use the static
3698 -- bounds of the base types to check. Disable this optimization
3699 -- in case of a descendant of a generic formal discrete type,
3700 -- because we don't necessarily know the upper bound yet.
3702 if Nkind
(Expr
) = N_Attribute_Reference
3703 and then Attribute_Name
(Expr
) = Name_Pos
3704 and then Is_Enumeration_Type
(Etype
(Prefix
(Expr
)))
3706 not Is_Generic_Type
(Root_Type
(Etype
(Prefix
(Expr
))))
3707 and then Is_Integer_Type
(Target_Type
)
3710 Enum_T
: constant Entity_Id
:=
3711 Root_Type
(Etype
(Prefix
(Expr
)));
3712 Int_T
: constant Entity_Id
:= Base_Type
(Target_Type
);
3713 Last_I
: constant Uint
:=
3714 Intval
(High_Bound
(Scalar_Range
(Int_T
)));
3718 -- Character types have no explicit literals, so we use
3719 -- the known number of characters in the type.
3721 if Root_Type
(Enum_T
) = Standard_Character
then
3722 Last_E
:= UI_From_Int
(255);
3724 elsif Enum_T
= Standard_Wide_Character
3725 or else Enum_T
= Standard_Wide_Wide_Character
3727 Last_E
:= UI_From_Int
(65535);
3732 (Entity
(High_Bound
(Scalar_Range
(Enum_T
))));
3735 if Last_E
> Last_I
then
3736 Activate_Overflow_Check
(N
);
3740 Activate_Overflow_Check
(N
);
3744 if not Range_Checks_Suppressed
(Target_Type
)
3745 and then not Range_Checks_Suppressed
(Expr_Type
)
3748 and then not GNATprove_Mode
3750 Apply_Float_Conversion_Check
(Expr
, Target_Type
);
3752 -- Raw conversions involving fixed-point types are expanded
3753 -- separately and do not need a Range_Check flag yet, except
3754 -- in GNATprove_Mode where this expansion is not performed.
3755 -- This does not apply to conversion where fixed-point types
3756 -- are treated as integers, which are precisely generated by
3761 or else (not Is_Fixed_Point_Type
(Expr_Type
)
3762 and then not Is_Fixed_Point_Type
(Target_Type
))
3764 Apply_Scalar_Range_Check
3765 (Expr
, Target_Type
, Fixed_Int
=> Conv_OK
);
3768 Set_Do_Range_Check
(Expr
, False);
3771 -- If the target type has predicates, we need to indicate
3772 -- the need for a check, even if Determine_Range finds that
3773 -- the value is within bounds. This may be the case e.g for
3774 -- a division with a constant denominator.
3776 if Has_Predicates
(Target_Type
) then
3777 Enable_Range_Check
(Expr
);
3783 -- Generate discriminant constraint checks for access types on the
3784 -- designated target type's stored constraints.
3786 -- Do we need to generate subtype predicate checks here as well ???
3788 elsif Comes_From_Source
(N
)
3789 and then Ekind
(Target_Type
) = E_General_Access_Type
3791 -- Check that both of the designated types have known discriminants,
3792 -- and that such checks on the target type are not suppressed.
3794 and then Has_Discriminants
(Directly_Designated_Type
(Target_Type
))
3795 and then Has_Discriminants
(Directly_Designated_Type
(Expr_Type
))
3796 and then not Discriminant_Checks_Suppressed
3797 (Directly_Designated_Type
(Target_Type
))
3799 -- Verify the designated type of the target has stored constraints
3802 (Stored_Constraint
(Directly_Designated_Type
(Target_Type
)))
3804 Make_Discriminant_Constraint_Check
3805 (Target_Type
=> Directly_Designated_Type
(Target_Type
),
3806 Expr_Type
=> Directly_Designated_Type
(Expr_Type
));
3808 -- Create discriminant checks for the Target_Type's stored constraints
3810 elsif Comes_From_Source
(N
)
3811 and then not Discriminant_Checks_Suppressed
(Target_Type
)
3812 and then Is_Record_Type
(Target_Type
)
3813 and then Is_Derived_Type
(Target_Type
)
3814 and then not Is_Tagged_Type
(Target_Type
)
3815 and then not Is_Constrained
(Target_Type
)
3816 and then Present
(Stored_Constraint
(Target_Type
))
3818 Make_Discriminant_Constraint_Check
(Target_Type
, Expr_Type
);
3820 -- For arrays, checks are set now, but conversions are applied during
3821 -- expansion, to take into accounts changes of representation. The
3822 -- checks become range checks on the base type or length checks on the
3823 -- subtype, depending on whether the target type is unconstrained or
3824 -- constrained. Note that the range check is put on the expression of a
3825 -- type conversion, while the length check is put on the type conversion
3828 elsif Is_Array_Type
(Target_Type
) then
3829 if Is_Constrained
(Target_Type
) then
3830 Set_Do_Length_Check
(N
);
3832 Set_Do_Range_Check
(Expr
);
3835 end Apply_Type_Conversion_Checks
;
3837 ----------------------------------------------
3838 -- Apply_Universal_Integer_Attribute_Checks --
3839 ----------------------------------------------
3841 procedure Apply_Universal_Integer_Attribute_Checks
(N
: Node_Id
) is
3842 Loc
: constant Source_Ptr
:= Sloc
(N
);
3843 Typ
: constant Entity_Id
:= Etype
(N
);
3846 if Inside_A_Generic
then
3849 -- Nothing to do if the result type is universal integer
3851 elsif Typ
= Universal_Integer
then
3854 -- Nothing to do if checks are suppressed
3856 elsif Range_Checks_Suppressed
(Typ
)
3857 and then Overflow_Checks_Suppressed
(Typ
)
3861 -- Nothing to do if the attribute does not come from source. The
3862 -- internal attributes we generate of this type do not need checks,
3863 -- and furthermore the attempt to check them causes some circular
3864 -- elaboration orders when dealing with packed types.
3866 elsif not Comes_From_Source
(N
) then
3869 -- If the prefix is a selected component that depends on a discriminant
3870 -- the check may improperly expose a discriminant instead of using
3871 -- the bounds of the object itself. Set the type of the attribute to
3872 -- the base type of the context, so that a check will be imposed when
3873 -- needed (e.g. if the node appears as an index).
3875 elsif Nkind
(Prefix
(N
)) = N_Selected_Component
3876 and then Ekind
(Typ
) = E_Signed_Integer_Subtype
3877 and then Depends_On_Discriminant
(Scalar_Range
(Typ
))
3879 Set_Etype
(N
, Base_Type
(Typ
));
3881 -- Otherwise, replace the attribute node with a type conversion node
3882 -- whose expression is the attribute, retyped to universal integer, and
3883 -- whose subtype mark is the target type. The call to analyze this
3884 -- conversion will set range and overflow checks as required for proper
3885 -- detection of an out of range value.
3888 Set_Etype
(N
, Universal_Integer
);
3889 Set_Analyzed
(N
, True);
3892 Make_Type_Conversion
(Loc
,
3893 Subtype_Mark
=> New_Occurrence_Of
(Typ
, Loc
),
3894 Expression
=> Relocate_Node
(N
)));
3896 Analyze_And_Resolve
(N
, Typ
);
3899 end Apply_Universal_Integer_Attribute_Checks
;
3901 -------------------------------------
3902 -- Atomic_Synchronization_Disabled --
3903 -------------------------------------
3905 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3906 -- using a bogus check called Atomic_Synchronization. This is to make it
3907 -- more convenient to get exactly the same semantics as [Un]Suppress.
3909 function Atomic_Synchronization_Disabled
(E
: Entity_Id
) return Boolean is
3911 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3912 -- looks enabled, since it is never disabled.
3914 if Debug_Flag_Dot_E
then
3917 -- If debug flag d.d is set then always return True, i.e. all atomic
3918 -- sync looks disabled, since it always tests True.
3920 elsif Debug_Flag_Dot_D
then
3923 -- If entity present, then check result for that entity
3925 elsif Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
3926 return Is_Check_Suppressed
(E
, Atomic_Synchronization
);
3928 -- Otherwise result depends on current scope setting
3931 return Scope_Suppress
.Suppress
(Atomic_Synchronization
);
3933 end Atomic_Synchronization_Disabled
;
3935 -------------------------------
3936 -- Build_Discriminant_Checks --
3937 -------------------------------
3939 function Build_Discriminant_Checks
3941 T_Typ
: Entity_Id
) return Node_Id
3943 Loc
: constant Source_Ptr
:= Sloc
(N
);
3946 Disc_Ent
: Entity_Id
;
3950 function Aggregate_Discriminant_Val
(Disc
: Entity_Id
) return Node_Id
;
3952 function Replace_Current_Instance
3953 (N
: Node_Id
) return Traverse_Result
;
3954 -- Replace a reference to the current instance of the type with the
3955 -- corresponding _init formal of the initialization procedure. Note:
3956 -- this function relies on us currently being within the initialization
3959 --------------------------------
3960 -- Aggregate_Discriminant_Val --
3961 --------------------------------
3963 function Aggregate_Discriminant_Val
(Disc
: Entity_Id
) return Node_Id
is
3967 -- The aggregate has been normalized with named associations. We use
3968 -- the Chars field to locate the discriminant to take into account
3969 -- discriminants in derived types, which carry the same name as those
3972 Assoc
:= First
(Component_Associations
(N
));
3973 while Present
(Assoc
) loop
3974 if Chars
(First
(Choices
(Assoc
))) = Chars
(Disc
) then
3975 return Expression
(Assoc
);
3981 -- Discriminant must have been found in the loop above
3983 raise Program_Error
;
3984 end Aggregate_Discriminant_Val
;
3986 ------------------------------
3987 -- Replace_Current_Instance --
3988 ------------------------------
3990 function Replace_Current_Instance
3991 (N
: Node_Id
) return Traverse_Result
is
3993 if Is_Entity_Name
(N
)
3994 and then Etype
(N
) = Entity
(N
)
3997 New_Occurrence_Of
(First_Formal
(Current_Subprogram
), Loc
));
4001 end Replace_Current_Instance
;
4003 procedure Search_And_Replace_Current_Instance
is new
4004 Traverse_Proc
(Replace_Current_Instance
);
4006 -- Start of processing for Build_Discriminant_Checks
4009 -- Loop through discriminants evolving the condition
4012 Disc
:= First_Elmt
(Discriminant_Constraint
(T_Typ
));
4014 -- For a fully private type, use the discriminants of the parent type
4016 if Is_Private_Type
(T_Typ
)
4017 and then No
(Full_View
(T_Typ
))
4019 Disc_Ent
:= First_Discriminant
(Etype
(Base_Type
(T_Typ
)));
4021 Disc_Ent
:= First_Discriminant
(T_Typ
);
4024 while Present
(Disc
) loop
4025 Dval
:= Node
(Disc
);
4027 if Nkind
(Dval
) = N_Identifier
4028 and then Ekind
(Entity
(Dval
)) = E_Discriminant
4030 Dval
:= New_Occurrence_Of
(Discriminal
(Entity
(Dval
)), Loc
);
4032 Dval
:= Duplicate_Subexpr_No_Checks
(Dval
);
4035 -- Replace references to the current instance of the type with the
4036 -- corresponding _init formal of the initialization procedure.
4038 if Within_Init_Proc
then
4039 Search_And_Replace_Current_Instance
(Dval
);
4042 -- If we have an Unchecked_Union node, we can infer the discriminants
4045 if Is_Unchecked_Union
(Base_Type
(T_Typ
)) then
4047 Get_Discriminant_Value
(
4048 First_Discriminant
(T_Typ
),
4050 Stored_Constraint
(T_Typ
)));
4052 elsif Nkind
(N
) = N_Aggregate
then
4054 Duplicate_Subexpr_No_Checks
4055 (Aggregate_Discriminant_Val
(Disc_Ent
));
4057 elsif Is_Access_Type
(Etype
(N
)) then
4059 Make_Selected_Component
(Loc
,
4061 Make_Explicit_Dereference
(Loc
,
4062 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True)),
4063 Selector_Name
=> Make_Identifier
(Loc
, Chars
(Disc_Ent
)));
4065 Set_Is_In_Discriminant_Check
(Dref
);
4068 Make_Selected_Component
(Loc
,
4070 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
4071 Selector_Name
=> Make_Identifier
(Loc
, Chars
(Disc_Ent
)));
4073 Set_Is_In_Discriminant_Check
(Dref
);
4076 Evolve_Or_Else
(Cond
,
4079 Right_Opnd
=> Dval
));
4082 Next_Discriminant
(Disc_Ent
);
4086 end Build_Discriminant_Checks
;
4092 function Check_Needed
(Nod
: Node_Id
; Check
: Check_Type
) return Boolean is
4099 function Left_Expression
(Op
: Node_Id
) return Node_Id
;
4100 -- Return the relevant expression from the left operand of the given
4101 -- short circuit form: this is LO itself, except if LO is a qualified
4102 -- expression, a type conversion, or an expression with actions, in
4103 -- which case this is Left_Expression (Expression (LO)).
4105 ---------------------
4106 -- Left_Expression --
4107 ---------------------
4109 function Left_Expression
(Op
: Node_Id
) return Node_Id
is
4110 LE
: Node_Id
:= Left_Opnd
(Op
);
4112 while Nkind
(LE
) in N_Qualified_Expression
4114 | N_Expression_With_Actions
4116 LE
:= Expression
(LE
);
4120 end Left_Expression
;
4122 -- Start of processing for Check_Needed
4125 -- Always check if not simple entity
4127 if Nkind
(Nod
) not in N_Has_Entity
4128 or else not Comes_From_Source
(Nod
)
4133 -- Look up tree for short circuit
4140 -- Done if out of subexpression (note that we allow generated stuff
4141 -- such as itype declarations in this context, to keep the loop going
4142 -- since we may well have generated such stuff in complex situations.
4143 -- Also done if no parent (probably an error condition, but no point
4144 -- in behaving nasty if we find it).
4147 or else (K
not in N_Subexpr
and then Comes_From_Source
(P
))
4151 -- Or/Or Else case, where test is part of the right operand, or is
4152 -- part of one of the actions associated with the right operand, and
4153 -- the left operand is an equality test.
4155 elsif K
= N_Op_Or
then
4156 exit when N
= Right_Opnd
(P
)
4157 and then Nkind
(Left_Expression
(P
)) = N_Op_Eq
;
4159 elsif K
= N_Or_Else
then
4160 exit when (N
= Right_Opnd
(P
)
4163 and then List_Containing
(N
) = Actions
(P
)))
4164 and then Nkind
(Left_Expression
(P
)) = N_Op_Eq
;
4166 -- Similar test for the And/And then case, where the left operand
4167 -- is an inequality test.
4169 elsif K
= N_Op_And
then
4170 exit when N
= Right_Opnd
(P
)
4171 and then Nkind
(Left_Expression
(P
)) = N_Op_Ne
;
4173 elsif K
= N_And_Then
then
4174 exit when (N
= Right_Opnd
(P
)
4177 and then List_Containing
(N
) = Actions
(P
)))
4178 and then Nkind
(Left_Expression
(P
)) = N_Op_Ne
;
4184 -- If we fall through the loop, then we have a conditional with an
4185 -- appropriate test as its left operand, so look further.
4187 L
:= Left_Expression
(P
);
4189 -- L is an "=" or "/=" operator: extract its operands
4191 R
:= Right_Opnd
(L
);
4194 -- Left operand of test must match original variable
4196 if Nkind
(L
) not in N_Has_Entity
or else Entity
(L
) /= Entity
(Nod
) then
4200 -- Right operand of test must be key value (zero or null)
4203 when Access_Check
=>
4204 if not Known_Null
(R
) then
4208 when Division_Check
=>
4209 if not Compile_Time_Known_Value
(R
)
4210 or else Expr_Value
(R
) /= Uint_0
4216 raise Program_Error
;
4219 -- Here we have the optimizable case, warn if not short-circuited
4221 if K
= N_Op_And
or else K
= N_Op_Or
then
4222 Error_Msg_Warn
:= SPARK_Mode
/= On
;
4225 when Access_Check
=>
4226 if GNATprove_Mode
then
4228 ("Constraint_Error might have been raised (access check)",
4232 ("Constraint_Error may be raised (access check)??",
4236 when Division_Check
=>
4237 if GNATprove_Mode
then
4239 ("Constraint_Error might have been raised (zero divide)",
4243 ("Constraint_Error may be raised (zero divide)??",
4248 raise Program_Error
;
4251 if K
= N_Op_And
then
4252 Error_Msg_N
-- CODEFIX
4253 ("use `AND THEN` instead of AND??", P
);
4255 Error_Msg_N
-- CODEFIX
4256 ("use `OR ELSE` instead of OR??", P
);
4259 -- If not short-circuited, we need the check
4263 -- If short-circuited, we can omit the check
4270 -----------------------------------
4271 -- Check_Valid_Lvalue_Subscripts --
4272 -----------------------------------
4274 procedure Check_Valid_Lvalue_Subscripts
(Expr
: Node_Id
) is
4276 -- Skip this if range checks are suppressed
4278 if Range_Checks_Suppressed
(Etype
(Expr
)) then
4281 -- Only do this check for expressions that come from source. We assume
4282 -- that expander generated assignments explicitly include any necessary
4283 -- checks. Note that this is not just an optimization, it avoids
4284 -- infinite recursions.
4286 elsif not Comes_From_Source
(Expr
) then
4289 -- For a selected component, check the prefix
4291 elsif Nkind
(Expr
) = N_Selected_Component
then
4292 Check_Valid_Lvalue_Subscripts
(Prefix
(Expr
));
4295 -- Case of indexed component
4297 elsif Nkind
(Expr
) = N_Indexed_Component
then
4298 Apply_Subscript_Validity_Checks
(Expr
);
4300 -- Prefix may itself be or contain an indexed component, and these
4301 -- subscripts need checking as well.
4303 Check_Valid_Lvalue_Subscripts
(Prefix
(Expr
));
4305 end Check_Valid_Lvalue_Subscripts
;
4307 ----------------------------------
4308 -- Null_Exclusion_Static_Checks --
4309 ----------------------------------
4311 procedure Null_Exclusion_Static_Checks
4313 Comp
: Node_Id
:= Empty
;
4314 Array_Comp
: Boolean := False)
4316 Has_Null
: constant Boolean := Has_Null_Exclusion
(N
);
4317 Kind
: constant Node_Kind
:= Nkind
(N
);
4318 Error_Nod
: Node_Id
;
4324 (Kind
in N_Component_Declaration
4325 | N_Discriminant_Specification
4326 | N_Function_Specification
4327 | N_Object_Declaration
4328 | N_Parameter_Specification
);
4330 if Kind
= N_Function_Specification
then
4331 Typ
:= Etype
(Defining_Entity
(N
));
4333 Typ
:= Etype
(Defining_Identifier
(N
));
4337 when N_Component_Declaration
=>
4338 if Present
(Access_Definition
(Component_Definition
(N
))) then
4339 Error_Nod
:= Component_Definition
(N
);
4341 Error_Nod
:= Subtype_Indication
(Component_Definition
(N
));
4344 when N_Discriminant_Specification
=>
4345 Error_Nod
:= Discriminant_Type
(N
);
4347 when N_Function_Specification
=>
4348 Error_Nod
:= Result_Definition
(N
);
4350 when N_Object_Declaration
=>
4351 Error_Nod
:= Object_Definition
(N
);
4353 when N_Parameter_Specification
=>
4354 Error_Nod
:= Parameter_Type
(N
);
4357 raise Program_Error
;
4362 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4363 -- applied to an access [sub]type.
4365 if not Is_Access_Type
(Typ
) then
4367 ("`NOT NULL` allowed only for an access type", Error_Nod
);
4369 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
4370 -- be applied to a [sub]type that does not exclude null already.
4372 elsif Can_Never_Be_Null
(Typ
) and then Comes_From_Source
(Typ
) then
4374 ("`NOT NULL` not allowed (& already excludes null)",
4379 -- Check that null-excluding objects are always initialized, except for
4380 -- deferred constants, for which the expression will appear in the full
4383 if Kind
= N_Object_Declaration
4384 and then No
(Expression
(N
))
4385 and then not Constant_Present
(N
)
4386 and then not No_Initialization
(N
)
4388 if Present
(Comp
) then
4390 -- Specialize the warning message to indicate that we are dealing
4391 -- with an uninitialized composite object that has a defaulted
4392 -- null-excluding component.
4394 Error_Msg_Name_1
:= Chars
(Defining_Identifier
(Comp
));
4395 Error_Msg_Name_2
:= Chars
(Defining_Identifier
(N
));
4398 (Compile_Time_Constraint_Error
4401 "(Ada 2005) null-excluding component % of object % must "
4402 & "be initialized??",
4403 Ent
=> Defining_Identifier
(Comp
)));
4405 -- This is a case of an array with null-excluding components, so
4406 -- indicate that in the warning.
4408 elsif Array_Comp
then
4410 (Compile_Time_Constraint_Error
4413 "(Ada 2005) null-excluding array components must "
4414 & "be initialized??",
4415 Ent
=> Defining_Identifier
(N
)));
4417 -- Normal case of object of a null-excluding access type
4420 -- Add an expression that assigns null. This node is needed by
4421 -- Apply_Compile_Time_Constraint_Error, which will replace this
4422 -- with a Constraint_Error node.
4424 Set_Expression
(N
, Make_Null
(Sloc
(N
)));
4425 Set_Etype
(Expression
(N
), Etype
(Defining_Identifier
(N
)));
4427 Apply_Compile_Time_Constraint_Error
4428 (N
=> Expression
(N
),
4430 "(Ada 2005) null-excluding objects must be initialized??",
4431 Reason
=> CE_Null_Not_Allowed
);
4435 -- Check that a null-excluding component, formal or object is not being
4436 -- assigned a null value. Otherwise generate a warning message and
4437 -- replace Expression (N) by an N_Constraint_Error node.
4439 if Kind
/= N_Function_Specification
then
4440 Expr
:= Expression
(N
);
4442 if Present
(Expr
) and then Known_Null
(Expr
) then
4444 when N_Component_Declaration
4445 | N_Discriminant_Specification
4447 Apply_Compile_Time_Constraint_Error
4450 "(Ada 2005) NULL not allowed in null-excluding "
4452 Reason
=> CE_Null_Not_Allowed
);
4454 when N_Object_Declaration
=>
4455 Apply_Compile_Time_Constraint_Error
4458 "(Ada 2005) NULL not allowed in null-excluding "
4460 Reason
=> CE_Null_Not_Allowed
);
4462 when N_Parameter_Specification
=>
4463 Apply_Compile_Time_Constraint_Error
4466 "(Ada 2005) NULL not allowed in null-excluding "
4468 Reason
=> CE_Null_Not_Allowed
);
4475 end Null_Exclusion_Static_Checks
;
4477 -------------------------------------
4478 -- Compute_Range_For_Arithmetic_Op --
4479 -------------------------------------
4481 procedure Compute_Range_For_Arithmetic_Op
4491 -- Use local variables for possible adjustments
4493 Llo
: Uint
renames Lo_Left
;
4494 Lhi
: Uint
renames Hi_Left
;
4495 Rlo
: Uint
:= Lo_Right
;
4496 Rhi
: Uint
:= Hi_Right
;
4499 -- We will compute a range for the result in almost all cases
4509 Hi
:= UI_Max
(abs Rlo
, abs Rhi
);
4521 -- If the right operand can only be zero, set 0..0
4523 if Rlo
= 0 and then Rhi
= 0 then
4527 -- Possible bounds of division must come from dividing end
4528 -- values of the input ranges (four possibilities), provided
4529 -- zero is not included in the possible values of the right
4532 -- Otherwise, we just consider two intervals of values for
4533 -- the right operand: the interval of negative values (up to
4534 -- -1) and the interval of positive values (starting at 1).
4535 -- Since division by 1 is the identity, and division by -1
4536 -- is negation, we get all possible bounds of division in that
4537 -- case by considering:
4538 -- - all values from the division of end values of input
4540 -- - the end values of the left operand;
4541 -- - the negation of the end values of the left operand.
4545 Mrk
: constant Uintp
.Save_Mark
:= Mark
;
4546 -- Mark so we can release the RR and Ev values
4554 -- Discard extreme values of zero for the divisor, since
4555 -- they will simply result in an exception in any case.
4563 -- Compute possible bounds coming from dividing end
4564 -- values of the input ranges.
4571 Lo
:= UI_Min
(UI_Min
(Ev1
, Ev2
), UI_Min
(Ev3
, Ev4
));
4572 Hi
:= UI_Max
(UI_Max
(Ev1
, Ev2
), UI_Max
(Ev3
, Ev4
));
4574 -- If the right operand can be both negative or positive,
4575 -- include the end values of the left operand in the
4576 -- extreme values, as well as their negation.
4578 if Rlo
< 0 and then Rhi
> 0 then
4585 UI_Min
(UI_Min
(Ev1
, Ev2
), UI_Min
(Ev3
, Ev4
)));
4587 UI_Max
(UI_Max
(Ev1
, Ev2
), UI_Max
(Ev3
, Ev4
)));
4590 -- Release the RR and Ev values
4592 Release_And_Save
(Mrk
, Lo
, Hi
);
4600 -- Discard negative values for the exponent, since they will
4601 -- simply result in an exception in any case.
4609 -- Estimate number of bits in result before we go computing
4610 -- giant useless bounds. Basically the number of bits in the
4611 -- result is the number of bits in the base multiplied by the
4612 -- value of the exponent. If this is big enough that the result
4613 -- definitely won't fit in Long_Long_Integer, return immediately
4614 -- and avoid computing giant bounds.
4616 -- The comparison here is approximate, but conservative, it
4617 -- only clicks on cases that are sure to exceed the bounds.
4619 if Num_Bits
(UI_Max
(abs Llo
, abs Lhi
)) * Rhi
+ 1 > 100 then
4625 -- If right operand is zero then result is 1
4632 -- High bound comes either from exponentiation of largest
4633 -- positive value to largest exponent value, or from
4634 -- the exponentiation of most negative value to an
4648 if Rhi
mod 2 = 0 then
4651 Hi2
:= Llo
** (Rhi
- 1);
4657 Hi
:= UI_Max
(Hi1
, Hi2
);
4660 -- Result can only be negative if base can be negative
4663 if Rhi
mod 2 = 0 then
4664 Lo
:= Llo
** (Rhi
- 1);
4669 -- Otherwise low bound is minimum ** minimum
4686 Maxabs
: constant Uint
:= UI_Max
(abs Rlo
, abs Rhi
) - 1;
4687 -- This is the maximum absolute value of the result
4693 -- The result depends only on the sign and magnitude of
4694 -- the right operand, it does not depend on the sign or
4695 -- magnitude of the left operand.
4708 when N_Op_Multiply
=>
4710 -- Possible bounds of multiplication must come from multiplying
4711 -- end values of the input ranges (four possibilities).
4714 Mrk
: constant Uintp
.Save_Mark
:= Mark
;
4715 -- Mark so we can release the Ev values
4717 Ev1
: constant Uint
:= Llo
* Rlo
;
4718 Ev2
: constant Uint
:= Llo
* Rhi
;
4719 Ev3
: constant Uint
:= Lhi
* Rlo
;
4720 Ev4
: constant Uint
:= Lhi
* Rhi
;
4723 Lo
:= UI_Min
(UI_Min
(Ev1
, Ev2
), UI_Min
(Ev3
, Ev4
));
4724 Hi
:= UI_Max
(UI_Max
(Ev1
, Ev2
), UI_Max
(Ev3
, Ev4
));
4726 -- Release the Ev values
4728 Release_And_Save
(Mrk
, Lo
, Hi
);
4731 -- Plus operator (affirmation)
4741 Maxabs
: constant Uint
:= UI_Max
(abs Rlo
, abs Rhi
) - 1;
4742 -- This is the maximum absolute value of the result. Note
4743 -- that the result range does not depend on the sign of the
4750 -- Case of left operand negative, which results in a range
4751 -- of -Maxabs .. 0 for those negative values. If there are
4752 -- no negative values then Lo value of result is always 0.
4758 -- Case of left operand positive
4767 when N_Op_Subtract
=>
4771 -- Nothing else should be possible
4774 raise Program_Error
;
4776 end Compute_Range_For_Arithmetic_Op
;
4778 ----------------------------------
4779 -- Conditional_Statements_Begin --
4780 ----------------------------------
4782 procedure Conditional_Statements_Begin
is
4784 Saved_Checks_TOS
:= Saved_Checks_TOS
+ 1;
4786 -- If stack overflows, kill all checks, that way we know to simply reset
4787 -- the number of saved checks to zero on return. This should never occur
4790 if Saved_Checks_TOS
> Saved_Checks_Stack
'Last then
4793 -- In the normal case, we just make a new stack entry saving the current
4794 -- number of saved checks for a later restore.
4797 Saved_Checks_Stack
(Saved_Checks_TOS
) := Num_Saved_Checks
;
4799 if Debug_Flag_CC
then
4800 w
("Conditional_Statements_Begin: Num_Saved_Checks = ",
4804 end Conditional_Statements_Begin
;
4806 --------------------------------
4807 -- Conditional_Statements_End --
4808 --------------------------------
4810 procedure Conditional_Statements_End
is
4812 pragma Assert
(Saved_Checks_TOS
> 0);
4814 -- If the saved checks stack overflowed, then we killed all checks, so
4815 -- setting the number of saved checks back to zero is correct. This
4816 -- should never occur in practice.
4818 if Saved_Checks_TOS
> Saved_Checks_Stack
'Last then
4819 Num_Saved_Checks
:= 0;
4821 -- In the normal case, restore the number of saved checks from the top
4825 Num_Saved_Checks
:= Saved_Checks_Stack
(Saved_Checks_TOS
);
4827 if Debug_Flag_CC
then
4828 w
("Conditional_Statements_End: Num_Saved_Checks = ",
4833 Saved_Checks_TOS
:= Saved_Checks_TOS
- 1;
4834 end Conditional_Statements_End
;
4836 -------------------------
4837 -- Convert_From_Bignum --
4838 -------------------------
4840 function Convert_From_Bignum
(N
: Node_Id
) return Node_Id
is
4841 Loc
: constant Source_Ptr
:= Sloc
(N
);
4844 pragma Assert
(Is_RTE
(Etype
(N
), RE_Bignum
));
4846 -- Construct call From Bignum
4849 Make_Function_Call
(Loc
,
4851 New_Occurrence_Of
(RTE
(RE_From_Bignum
), Loc
),
4852 Parameter_Associations
=> New_List
(Relocate_Node
(N
)));
4853 end Convert_From_Bignum
;
4855 -----------------------
4856 -- Convert_To_Bignum --
4857 -----------------------
4859 function Convert_To_Bignum
(N
: Node_Id
) return Node_Id
is
4860 Loc
: constant Source_Ptr
:= Sloc
(N
);
4863 -- Nothing to do if Bignum already except call Relocate_Node
4865 if Is_RTE
(Etype
(N
), RE_Bignum
) then
4866 return Relocate_Node
(N
);
4868 -- Otherwise construct call to To_Bignum, converting the operand to the
4869 -- required Long_Long_Integer form.
4872 pragma Assert
(Is_Signed_Integer_Type
(Etype
(N
)));
4874 Make_Function_Call
(Loc
,
4876 New_Occurrence_Of
(RTE
(RE_To_Bignum
), Loc
),
4877 Parameter_Associations
=> New_List
(
4878 Convert_To
(Standard_Long_Long_Integer
, Relocate_Node
(N
))));
4880 end Convert_To_Bignum
;
4882 ---------------------
4883 -- Determine_Range --
4884 ---------------------
4886 Cache_Size
: constant := 2 ** 10;
4887 type Cache_Index
is range 0 .. Cache_Size
- 1;
4888 -- Determine size of below cache (power of 2 is more efficient)
4890 Determine_Range_Cache_N
: array (Cache_Index
) of Node_Id
;
4891 Determine_Range_Cache_O
: array (Cache_Index
) of Node_Id
;
4892 Determine_Range_Cache_V
: array (Cache_Index
) of Boolean;
4893 Determine_Range_Cache_Lo
: array (Cache_Index
) of Uint
;
4894 Determine_Range_Cache_Hi
: array (Cache_Index
) of Uint
;
4895 Determine_Range_Cache_Lo_R
: array (Cache_Index
) of Ureal
;
4896 Determine_Range_Cache_Hi_R
: array (Cache_Index
) of Ureal
;
4897 -- The above arrays are used to implement a small direct cache for
4898 -- Determine_Range and Determine_Range_R calls. Because of the way these
4899 -- subprograms recursively traces subexpressions, and because overflow
4900 -- checking calls the routine on the way up the tree, a quadratic behavior
4901 -- can otherwise be encountered in large expressions. The cache entry for
4902 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4903 -- by checking the actual node value stored there. The Range_Cache_O array
4904 -- records the setting of Original_Node (N) so that the cache entry does
4905 -- not become stale when the node N is rewritten. The Range_Cache_V array
4906 -- records the setting of Assume_Valid for the cache entry.
4908 procedure Determine_Range
4913 Assume_Valid
: Boolean := False)
4915 Kind
: constant Node_Kind
:= Nkind
(N
);
4918 function Half_Address_Space
return Uint
;
4919 -- The size of half the total addressable memory space in storage units
4920 -- (minus one, so that the size fits in a signed integer whose size is
4921 -- System_Address_Size, which helps in various cases).
4923 ------------------------
4924 -- Half_Address_Space --
4925 ------------------------
4927 function Half_Address_Space
return Uint
is
4929 return Uint_2
** (System_Address_Size
- 1) - 1;
4930 end Half_Address_Space
;
4934 Typ
: Entity_Id
:= Etype
(N
);
4935 -- Type to use, may get reset to base type for possibly invalid entity
4937 Lo_Left
: Uint
:= No_Uint
;
4938 Hi_Left
: Uint
:= No_Uint
;
4939 -- Lo and Hi bounds of left operand
4941 Lo_Right
: Uint
:= No_Uint
;
4942 Hi_Right
: Uint
:= No_Uint
;
4943 -- Lo and Hi bounds of right (or only) operand
4946 -- Temp variable used to hold a bound node
4949 -- High bound of base type of expression
4953 -- Refined values for low and high bounds, after tightening
4956 -- Used in lower level calls to indicate if call succeeded
4958 Cindex
: Cache_Index
;
4959 -- Used to search cache
4964 -- Start of processing for Determine_Range
4967 -- Prevent junk warnings by initializing range variables
4974 -- For temporary constants internally generated to remove side effects
4975 -- we must use the corresponding expression to determine the range of
4976 -- the expression. But note that the expander can also generate
4977 -- constants in other cases, including deferred constants.
4979 if Is_Entity_Name
(N
)
4980 and then Nkind
(Parent
(Entity
(N
))) = N_Object_Declaration
4981 and then Ekind
(Entity
(N
)) = E_Constant
4982 and then Is_Internal_Name
(Chars
(Entity
(N
)))
4984 if Present
(Expression
(Parent
(Entity
(N
)))) then
4986 (Expression
(Parent
(Entity
(N
))), OK
, Lo
, Hi
, Assume_Valid
);
4988 elsif Present
(Full_View
(Entity
(N
))) then
4990 (Expression
(Parent
(Full_View
(Entity
(N
)))),
4991 OK
, Lo
, Hi
, Assume_Valid
);
4999 -- If type is not defined, we can't determine its range
5003 -- We don't deal with anything except discrete types
5005 or else not Is_Discrete_Type
(Typ
)
5007 -- Don't deal with enumerated types with non-standard representation
5009 or else (Is_Enumeration_Type
(Typ
)
5010 and then Present
(Enum_Pos_To_Rep
5011 (Implementation_Base_Type
(Typ
))))
5013 -- Ignore type for which an error has been posted, since range in
5014 -- this case may well be a bogosity deriving from the error. Also
5015 -- ignore if error posted on the reference node.
5017 or else Error_Posted
(N
) or else Error_Posted
(Typ
)
5023 -- For all other cases, we can determine the range
5027 -- If value is compile time known, then the possible range is the one
5028 -- value that we know this expression definitely has.
5030 if Compile_Time_Known_Value
(N
) then
5031 Lo
:= Expr_Value
(N
);
5036 -- Return if already in the cache
5038 Cindex
:= Cache_Index
(N
mod Cache_Size
);
5040 if Determine_Range_Cache_N
(Cindex
) = N
5042 Determine_Range_Cache_O
(Cindex
) = Original_Node
(N
)
5044 Determine_Range_Cache_V
(Cindex
) = Assume_Valid
5046 Lo
:= Determine_Range_Cache_Lo
(Cindex
);
5047 Hi
:= Determine_Range_Cache_Hi
(Cindex
);
5051 -- Otherwise, start by finding the bounds of the type of the expression,
5052 -- the value cannot be outside this range (if it is, then we have an
5053 -- overflow situation, which is a separate check, we are talking here
5054 -- only about the expression value).
5056 -- First a check, never try to find the bounds of a generic type, since
5057 -- these bounds are always junk values, and it is only valid to look at
5058 -- the bounds in an instance.
5060 if Is_Generic_Type
(Typ
) then
5065 -- First step, change to use base type unless we know the value is valid
5067 if (Is_Entity_Name
(N
) and then Is_Known_Valid
(Entity
(N
)))
5068 or else Assume_No_Invalid_Values
5069 or else Assume_Valid
5071 -- If this is a known valid constant with a nonstatic value, it may
5072 -- have inherited a narrower subtype from its initial value; use this
5073 -- saved subtype (see sem_ch3.adb).
5075 if Is_Entity_Name
(N
)
5076 and then Ekind
(Entity
(N
)) = E_Constant
5077 and then Present
(Actual_Subtype
(Entity
(N
)))
5079 Typ
:= Actual_Subtype
(Entity
(N
));
5083 Typ
:= Underlying_Type
(Base_Type
(Typ
));
5086 -- Retrieve the base type. Handle the case where the base type is a
5087 -- private enumeration type.
5089 Btyp
:= Base_Type
(Typ
);
5091 if Is_Private_Type
(Btyp
) and then Present
(Full_View
(Btyp
)) then
5092 Btyp
:= Full_View
(Btyp
);
5095 -- We use the actual bound unless it is dynamic, in which case use the
5096 -- corresponding base type bound if possible. If we can't get a bound
5097 -- then we figure we can't determine the range (a peculiar case, that
5098 -- perhaps cannot happen, but there is no point in bombing in this
5099 -- optimization circuit).
5101 -- First the low bound
5103 Bound
:= Type_Low_Bound
(Typ
);
5105 if Compile_Time_Known_Value
(Bound
) then
5106 Lo
:= Expr_Value
(Bound
);
5108 elsif Compile_Time_Known_Value
(Type_Low_Bound
(Btyp
)) then
5109 Lo
:= Expr_Value
(Type_Low_Bound
(Btyp
));
5116 -- Now the high bound
5118 Bound
:= Type_High_Bound
(Typ
);
5120 -- We need the high bound of the base type later on, and this should
5121 -- always be compile time known. Again, it is not clear that this
5122 -- can ever be false, but no point in bombing.
5124 if Compile_Time_Known_Value
(Type_High_Bound
(Btyp
)) then
5125 Hbound
:= Expr_Value
(Type_High_Bound
(Btyp
));
5133 -- If we have a static subtype, then that may have a tighter bound so
5134 -- use the upper bound of the subtype instead in this case.
5136 if Compile_Time_Known_Value
(Bound
) then
5137 Hi
:= Expr_Value
(Bound
);
5140 -- We may be able to refine this value in certain situations. If any
5141 -- refinement is possible, then Lor and Hir are set to possibly tighter
5142 -- bounds, and OK1 is set to True.
5146 -- Unary operation case
5153 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
5156 Compute_Range_For_Arithmetic_Op
5157 (Kind
, Lo_Left
, Hi_Left
, Lo_Right
, Hi_Right
, OK1
, Lor
, Hir
);
5160 -- Binary operation case
5171 (Left_Opnd
(N
), OK1
, Lo_Left
, Hi_Left
, Assume_Valid
);
5175 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
5179 Compute_Range_For_Arithmetic_Op
5180 (Kind
, Lo_Left
, Hi_Left
, Lo_Right
, Hi_Right
, OK1
, Lor
, Hir
);
5183 -- Attribute reference cases
5185 when N_Attribute_Reference
=>
5186 case Get_Attribute_Id
(Attribute_Name
(N
)) is
5188 -- For Min/Max attributes, we can refine the range using the
5189 -- possible range of values of the attribute expressions.
5195 (First
(Expressions
(N
)),
5196 OK1
, Lo_Left
, Hi_Left
, Assume_Valid
);
5200 (Next
(First
(Expressions
(N
))),
5201 OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
5205 Lor
:= UI_Min
(Lo_Left
, Lo_Right
);
5206 Hir
:= UI_Max
(Hi_Left
, Hi_Right
);
5209 -- For Pos/Val attributes, we can refine the range using the
5210 -- possible range of values of the attribute expression.
5216 (First
(Expressions
(N
)), OK1
, Lor
, Hir
, Assume_Valid
);
5218 -- For Length and Range_Length attributes, use the bounds of
5219 -- the (corresponding index) type to refine the range.
5221 when Attribute_Length
5222 | Attribute_Range_Length
5232 Ptyp
:= Etype
(Prefix
(N
));
5233 if Is_Access_Type
(Ptyp
) then
5234 Ptyp
:= Designated_Type
(Ptyp
);
5237 -- For string literal, we know exact value
5239 if Ekind
(Ptyp
) = E_String_Literal_Subtype
then
5241 Lo
:= String_Literal_Length
(Ptyp
);
5242 Hi
:= String_Literal_Length
(Ptyp
);
5246 if Is_Array_Type
(Ptyp
) then
5247 Ityp
:= Get_Index_Subtype
(N
);
5252 -- If the (index) type is a formal type or derived from
5253 -- one, the bounds are not static.
5255 if Is_Generic_Type
(Root_Type
(Ityp
)) then
5261 (Type_Low_Bound
(Ityp
), OK1
, LL
, LU
, Assume_Valid
);
5265 (Type_High_Bound
(Ityp
), OK1
, UL
, UU
, Assume_Valid
);
5268 -- The maximum value for Length is the biggest
5269 -- possible gap between the values of the bounds.
5270 -- But of course, this value cannot be negative.
5272 Hir
:= UI_Max
(Uint_0
, UU
- LL
+ 1);
5274 -- For a constrained array, the minimum value for
5275 -- Length is taken from the actual value of the
5276 -- bounds, since the index will be exactly of this
5279 if Is_Constrained
(Ptyp
) then
5280 Lor
:= UI_Max
(Uint_0
, UL
- LU
+ 1);
5282 -- For an unconstrained array, the minimum value
5283 -- for length is always zero.
5291 -- Small optimization: the maximum size in storage units
5292 -- an object can have with GNAT is half of the address
5293 -- space, so we can bound the length of an array declared
5294 -- in Interfaces (or its children) because its component
5295 -- size is at least the storage unit and it is meant to
5296 -- be used to interface actual array objects.
5298 if Is_Array_Type
(Ptyp
) then
5300 S
: constant Entity_Id
:= Scope
(Base_Type
(Ptyp
));
5302 if Is_RTU
(S
, Interfaces
)
5303 or else (S
/= Standard_Standard
5304 and then Is_RTU
(Scope
(S
), Interfaces
))
5306 Hir
:= UI_Min
(Hir
, Half_Address_Space
);
5312 -- The maximum default alignment is quite low, but GNAT accepts
5313 -- alignment clauses that are fairly large, but not as large as
5314 -- the maximum size of objects, see below.
5316 when Attribute_Alignment
=>
5318 Hir
:= Half_Address_Space
;
5321 -- The attribute should have been folded if a component clause
5322 -- was specified, so we assume there is none.
5325 | Attribute_First_Bit
5328 Hir
:= UI_From_Int
(System_Storage_Unit
- 1);
5331 -- Likewise about the component clause. Note that Last_Bit
5332 -- yields -1 for a field of size 0 if First_Bit is 0.
5334 when Attribute_Last_Bit
=>
5335 Lor
:= Uint_Minus_1
;
5339 -- Likewise about the component clause for Position. The
5340 -- maximum size in storage units that an object can have
5341 -- with GNAT is half of the address space.
5343 when Attribute_Max_Size_In_Storage_Elements
5344 | Attribute_Position
5347 Hir
:= Half_Address_Space
;
5350 -- These attributes yield a nonnegative value (we do not set
5351 -- the maximum value because it is too large to be useful).
5353 when Attribute_Bit_Position
5354 | Attribute_Component_Size
5355 | Attribute_Object_Size
5357 | Attribute_Value_Size
5363 -- The maximum size is the sum of twice the size of the largest
5364 -- integer for every dimension, rounded up to the next multiple
5365 -- of the maximum alignment, but we add instead of rounding.
5367 when Attribute_Descriptor_Size
=>
5369 Max_Align
: constant Pos
:=
5370 Maximum_Alignment
* System_Storage_Unit
;
5371 Max_Size
: constant Uint
:=
5372 2 * Esize
(Universal_Integer
);
5373 Ndims
: constant Pos
:=
5374 Number_Dimensions
(Etype
(Prefix
(N
)));
5377 Hir
:= Max_Size
* Ndims
+ Max_Align
;
5381 -- No special handling for other attributes for now
5388 when N_Type_Conversion
=>
5389 -- For a type conversion, we can try to refine the range using the
5392 Determine_Range_To_Discrete
5393 (Expression
(N
), OK1
, Lor
, Hir
, Conversion_OK
(N
), Assume_Valid
);
5395 -- Nothing special to do for all other expression kinds
5403 -- At this stage, if OK1 is true, then we know that the actual result of
5404 -- the computed expression is in the range Lor .. Hir. We can use this
5405 -- to restrict the possible range of results.
5409 -- If the refined value of the low bound is greater than the type
5410 -- low bound, then reset it to the more restrictive value. However,
5411 -- we do NOT do this for the case of a modular type where the
5412 -- possible upper bound on the value is above the base type high
5413 -- bound, because that means the result could wrap.
5414 -- Same applies for the lower bound if it is negative.
5416 if Is_Modular_Integer_Type
(Typ
) then
5417 if Lor
> Lo
and then Hir
<= Hbound
then
5421 if Hir
< Hi
and then Lor
>= Uint_0
then
5426 if Lor
> Hi
or else Hir
< Lo
then
5428 -- If the ranges are disjoint, return the computed range.
5430 -- The current range-constraining logic would require returning
5431 -- the base type's bounds. However, this would miss an
5432 -- opportunity to warn about out-of-range values for some cases
5433 -- (e.g. when type's upper bound is equal to base type upper
5436 -- The alternative of always returning the computed values,
5437 -- even when ranges are intersecting, has unwanted effects
5438 -- (mainly useless constraint checks are inserted) in the
5439 -- Enable_Overflow_Check and Apply_Scalar_Range_Check as these
5440 -- bounds have a special interpretation.
5446 -- If the ranges Lor .. Hir and Lo .. Hi intersect, try to
5447 -- refine the returned range.
5460 -- Set cache entry for future call and we are all done
5462 Determine_Range_Cache_N
(Cindex
) := N
;
5463 Determine_Range_Cache_O
(Cindex
) := Original_Node
(N
);
5464 Determine_Range_Cache_V
(Cindex
) := Assume_Valid
;
5465 Determine_Range_Cache_Lo
(Cindex
) := Lo
;
5466 Determine_Range_Cache_Hi
(Cindex
) := Hi
;
5469 -- If any exception occurs, it means that we have some bug in the compiler,
5470 -- possibly triggered by a previous error, or by some unforeseen peculiar
5471 -- occurrence. However, this is only an optimization attempt, so there is
5472 -- really no point in crashing the compiler. Instead we just decide, too
5473 -- bad, we can't figure out a range in this case after all.
5478 -- Debug flag K disables this behavior (useful for debugging)
5480 if Debug_Flag_K
then
5488 end Determine_Range
;
5490 -----------------------
5491 -- Determine_Range_R --
5492 -----------------------
5494 procedure Determine_Range_R
5499 Assume_Valid
: Boolean := False)
5501 Typ
: Entity_Id
:= Etype
(N
);
5502 -- Type to use, may get reset to base type for possibly invalid entity
5506 -- Lo and Hi bounds of left operand
5508 Lo_Right
: Ureal
:= No_Ureal
;
5509 Hi_Right
: Ureal
:= No_Ureal
;
5510 -- Lo and Hi bounds of right (or only) operand
5513 -- Temp variable used to hold a bound node
5516 -- High bound of base type of expression
5520 -- Refined values for low and high bounds, after tightening
5523 -- Used in lower level calls to indicate if call succeeded
5525 Cindex
: Cache_Index
;
5526 -- Used to search cache
5531 function OK_Operands
return Boolean;
5532 -- Used for binary operators. Determines the ranges of the left and
5533 -- right operands, and if they are both OK, returns True, and puts
5534 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
5536 function Round_Machine
(B
: Ureal
) return Ureal
;
5537 -- B is a real bound. Round it to the nearest machine number.
5543 function OK_Operands
return Boolean is
5546 (Left_Opnd
(N
), OK1
, Lo_Left
, Hi_Left
, Assume_Valid
);
5553 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
5561 function Round_Machine
(B
: Ureal
) return Ureal
is
5563 return Machine_Number
(Typ
, B
, N
);
5566 -- Start of processing for Determine_Range_R
5569 -- Prevent junk warnings by initializing range variables
5576 -- For temporary constants internally generated to remove side effects
5577 -- we must use the corresponding expression to determine the range of
5578 -- the expression. But note that the expander can also generate
5579 -- constants in other cases, including deferred constants.
5581 if Is_Entity_Name
(N
)
5582 and then Nkind
(Parent
(Entity
(N
))) = N_Object_Declaration
5583 and then Ekind
(Entity
(N
)) = E_Constant
5584 and then Is_Internal_Name
(Chars
(Entity
(N
)))
5586 if Present
(Expression
(Parent
(Entity
(N
)))) then
5588 (Expression
(Parent
(Entity
(N
))), OK
, Lo
, Hi
, Assume_Valid
);
5590 elsif Present
(Full_View
(Entity
(N
))) then
5592 (Expression
(Parent
(Full_View
(Entity
(N
)))),
5593 OK
, Lo
, Hi
, Assume_Valid
);
5602 -- If type is not defined, we can't determine its range
5604 pragma Warnings
(Off
, "condition can only be True if invalid");
5605 -- Otherwise the compiler warns on the check of Float_Rep below, because
5606 -- there is only one value (see types.ads).
5610 -- We don't deal with anything except IEEE floating-point types
5612 or else not Is_Floating_Point_Type
(Typ
)
5613 or else Float_Rep
(Typ
) /= IEEE_Binary
5615 -- Ignore type for which an error has been posted, since range in
5616 -- this case may well be a bogosity deriving from the error. Also
5617 -- ignore if error posted on the reference node.
5619 or else Error_Posted
(N
) or else Error_Posted
(Typ
)
5621 pragma Warnings
(On
, "condition can only be True if invalid");
5626 -- For all other cases, we can determine the range
5630 -- If value is compile time known, then the possible range is the one
5631 -- value that we know this expression definitely has.
5633 if Compile_Time_Known_Value
(N
) then
5634 Lo
:= Expr_Value_R
(N
);
5639 -- Return if already in the cache
5641 Cindex
:= Cache_Index
(N
mod Cache_Size
);
5643 if Determine_Range_Cache_N
(Cindex
) = N
5645 Determine_Range_Cache_O
(Cindex
) = Original_Node
(N
)
5647 Determine_Range_Cache_V
(Cindex
) = Assume_Valid
5649 Lo
:= Determine_Range_Cache_Lo_R
(Cindex
);
5650 Hi
:= Determine_Range_Cache_Hi_R
(Cindex
);
5654 -- Otherwise, start by finding the bounds of the type of the expression,
5655 -- the value cannot be outside this range (if it is, then we have an
5656 -- overflow situation, which is a separate check, we are talking here
5657 -- only about the expression value).
5659 -- First a check, never try to find the bounds of a generic type, since
5660 -- these bounds are always junk values, and it is only valid to look at
5661 -- the bounds in an instance.
5663 if Is_Generic_Type
(Typ
) then
5668 -- First step, change to use base type unless we know the value is valid
5670 if (Is_Entity_Name
(N
) and then Is_Known_Valid
(Entity
(N
)))
5671 or else Assume_No_Invalid_Values
5672 or else Assume_Valid
5676 Typ
:= Underlying_Type
(Base_Type
(Typ
));
5679 -- Retrieve the base type. Handle the case where the base type is a
5682 Btyp
:= Base_Type
(Typ
);
5684 if Is_Private_Type
(Btyp
) and then Present
(Full_View
(Btyp
)) then
5685 Btyp
:= Full_View
(Btyp
);
5688 -- We use the actual bound unless it is dynamic, in which case use the
5689 -- corresponding base type bound if possible. If we can't get a bound
5690 -- then we figure we can't determine the range (a peculiar case, that
5691 -- perhaps cannot happen, but there is no point in bombing in this
5692 -- optimization circuit).
5694 -- First the low bound
5696 Bound
:= Type_Low_Bound
(Typ
);
5698 if Compile_Time_Known_Value
(Bound
) then
5699 Lo
:= Expr_Value_R
(Bound
);
5701 elsif Compile_Time_Known_Value
(Type_Low_Bound
(Btyp
)) then
5702 Lo
:= Expr_Value_R
(Type_Low_Bound
(Btyp
));
5709 -- Now the high bound
5711 Bound
:= Type_High_Bound
(Typ
);
5713 -- We need the high bound of the base type later on, and this should
5714 -- always be compile time known. Again, it is not clear that this
5715 -- can ever be false, but no point in bombing.
5717 if Compile_Time_Known_Value
(Type_High_Bound
(Btyp
)) then
5718 Hbound
:= Expr_Value_R
(Type_High_Bound
(Btyp
));
5726 -- If we have a static subtype, then that may have a tighter bound so
5727 -- use the upper bound of the subtype instead in this case.
5729 if Compile_Time_Known_Value
(Bound
) then
5730 Hi
:= Expr_Value_R
(Bound
);
5733 -- We may be able to refine this value in certain situations. If any
5734 -- refinement is possible, then Lor and Hir are set to possibly tighter
5735 -- bounds, and OK1 is set to True.
5739 -- For unary plus, result is limited by range of operand
5743 (Right_Opnd
(N
), OK1
, Lor
, Hir
, Assume_Valid
);
5745 -- For unary minus, determine range of operand, and negate it
5749 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
5756 -- For binary addition, get range of each operand and do the
5757 -- addition to get the result range.
5761 Lor
:= Round_Machine
(Lo_Left
+ Lo_Right
);
5762 Hir
:= Round_Machine
(Hi_Left
+ Hi_Right
);
5765 -- For binary subtraction, get range of each operand and do the worst
5766 -- case subtraction to get the result range.
5768 when N_Op_Subtract
=>
5770 Lor
:= Round_Machine
(Lo_Left
- Hi_Right
);
5771 Hir
:= Round_Machine
(Hi_Left
- Lo_Right
);
5774 -- For multiplication, get range of each operand and do the
5775 -- four multiplications to get the result range.
5777 when N_Op_Multiply
=>
5780 M1
: constant Ureal
:= Round_Machine
(Lo_Left
* Lo_Right
);
5781 M2
: constant Ureal
:= Round_Machine
(Lo_Left
* Hi_Right
);
5782 M3
: constant Ureal
:= Round_Machine
(Hi_Left
* Lo_Right
);
5783 M4
: constant Ureal
:= Round_Machine
(Hi_Left
* Hi_Right
);
5786 Lor
:= UR_Min
(UR_Min
(M1
, M2
), UR_Min
(M3
, M4
));
5787 Hir
:= UR_Max
(UR_Max
(M1
, M2
), UR_Max
(M3
, M4
));
5791 -- For division, consider separately the cases where the right
5792 -- operand is positive or negative. Otherwise, the right operand
5793 -- can be arbitrarily close to zero, so the result is likely to
5794 -- be unbounded in one direction, do not attempt to compute it.
5799 -- Right operand is positive
5801 if Lo_Right
> Ureal_0
then
5803 -- If the low bound of the left operand is negative, obtain
5804 -- the overall low bound by dividing it by the smallest
5805 -- value of the right operand, and otherwise by the largest
5806 -- value of the right operand.
5808 if Lo_Left
< Ureal_0
then
5809 Lor
:= Round_Machine
(Lo_Left
/ Lo_Right
);
5811 Lor
:= Round_Machine
(Lo_Left
/ Hi_Right
);
5814 -- If the high bound of the left operand is negative, obtain
5815 -- the overall high bound by dividing it by the largest
5816 -- value of the right operand, and otherwise by the
5817 -- smallest value of the right operand.
5819 if Hi_Left
< Ureal_0
then
5820 Hir
:= Round_Machine
(Hi_Left
/ Hi_Right
);
5822 Hir
:= Round_Machine
(Hi_Left
/ Lo_Right
);
5825 -- Right operand is negative
5827 elsif Hi_Right
< Ureal_0
then
5829 -- If the low bound of the left operand is negative, obtain
5830 -- the overall low bound by dividing it by the largest
5831 -- value of the right operand, and otherwise by the smallest
5832 -- value of the right operand.
5834 if Lo_Left
< Ureal_0
then
5835 Lor
:= Round_Machine
(Lo_Left
/ Hi_Right
);
5837 Lor
:= Round_Machine
(Lo_Left
/ Lo_Right
);
5840 -- If the high bound of the left operand is negative, obtain
5841 -- the overall high bound by dividing it by the smallest
5842 -- value of the right operand, and otherwise by the
5843 -- largest value of the right operand.
5845 if Hi_Left
< Ureal_0
then
5846 Hir
:= Round_Machine
(Hi_Left
/ Lo_Right
);
5848 Hir
:= Round_Machine
(Hi_Left
/ Hi_Right
);
5856 when N_Type_Conversion
=>
5858 -- For type conversion from one floating-point type to another, we
5859 -- can refine the range using the converted value.
5861 if Is_Floating_Point_Type
(Etype
(Expression
(N
))) then
5862 Determine_Range_R
(Expression
(N
), OK1
, Lor
, Hir
, Assume_Valid
);
5864 -- When converting an integer to a floating-point type, determine
5865 -- the range in integer first, and then convert the bounds.
5867 elsif Is_Discrete_Type
(Etype
(Expression
(N
))) then
5874 (Expression
(N
), OK1
, Lor_Int
, Hir_Int
, Assume_Valid
);
5877 Lor
:= Round_Machine
(UR_From_Uint
(Lor_Int
));
5878 Hir
:= Round_Machine
(UR_From_Uint
(Hir_Int
));
5886 -- Nothing special to do for all other expression kinds
5894 -- At this stage, if OK1 is true, then we know that the actual result of
5895 -- the computed expression is in the range Lor .. Hir. We can use this
5896 -- to restrict the possible range of results.
5900 -- If the refined value of the low bound is greater than the type
5901 -- low bound, then reset it to the more restrictive value.
5907 -- Similarly, if the refined value of the high bound is less than the
5908 -- value so far, then reset it to the more restrictive value.
5915 -- Set cache entry for future call and we are all done
5917 Determine_Range_Cache_N
(Cindex
) := N
;
5918 Determine_Range_Cache_O
(Cindex
) := Original_Node
(N
);
5919 Determine_Range_Cache_V
(Cindex
) := Assume_Valid
;
5920 Determine_Range_Cache_Lo_R
(Cindex
) := Lo
;
5921 Determine_Range_Cache_Hi_R
(Cindex
) := Hi
;
5924 -- If any exception occurs, it means that we have some bug in the compiler,
5925 -- possibly triggered by a previous error, or by some unforeseen peculiar
5926 -- occurrence. However, this is only an optimization attempt, so there is
5927 -- really no point in crashing the compiler. Instead we just decide, too
5928 -- bad, we can't figure out a range in this case after all.
5933 -- Debug flag K disables this behavior (useful for debugging)
5935 if Debug_Flag_K
then
5943 end Determine_Range_R
;
5945 ---------------------------------
5946 -- Determine_Range_To_Discrete --
5947 ---------------------------------
5949 procedure Determine_Range_To_Discrete
5954 Fixed_Int
: Boolean := False;
5955 Assume_Valid
: Boolean := False)
5957 Typ
: constant Entity_Id
:= Etype
(N
);
5960 -- For a discrete type, simply defer to Determine_Range
5962 if Is_Discrete_Type
(Typ
) then
5963 Determine_Range
(N
, OK
, Lo
, Hi
, Assume_Valid
);
5965 -- For a fixed point type treated as an integer, we can determine the
5966 -- range using the Corresponding_Integer_Value of the bounds of the
5967 -- type or base type. This is done by the calls to Expr_Value below.
5969 elsif Is_Fixed_Point_Type
(Typ
) and then Fixed_Int
then
5971 Btyp
, Ftyp
: Entity_Id
;
5975 if Assume_Valid
then
5978 Ftyp
:= Underlying_Type
(Base_Type
(Typ
));
5981 Btyp
:= Base_Type
(Ftyp
);
5983 -- First the low bound
5985 Bound
:= Type_Low_Bound
(Ftyp
);
5987 if Compile_Time_Known_Value
(Bound
) then
5988 Lo
:= Expr_Value
(Bound
);
5990 Lo
:= Expr_Value
(Type_Low_Bound
(Btyp
));
5993 -- Then the high bound
5995 Bound
:= Type_High_Bound
(Ftyp
);
5997 if Compile_Time_Known_Value
(Bound
) then
5998 Hi
:= Expr_Value
(Bound
);
6000 Hi
:= Expr_Value
(Type_High_Bound
(Btyp
));
6006 -- For a floating-point type, we can determine the range in real first,
6007 -- and then convert the bounds using UR_To_Uint, which correctly rounds
6008 -- away from zero when half way between two integers, as required by
6009 -- normal Ada 95 rounding semantics. But this is only possible because
6010 -- GNATprove's analysis rules out the possibility of a NaN or infinite.
6012 elsif GNATprove_Mode
and then Is_Floating_Point_Type
(Typ
) then
6014 Lo_Real
, Hi_Real
: Ureal
;
6017 Determine_Range_R
(N
, OK
, Lo_Real
, Hi_Real
, Assume_Valid
);
6020 Lo
:= UR_To_Uint
(Lo_Real
);
6021 Hi
:= UR_To_Uint
(Hi_Real
);
6033 end Determine_Range_To_Discrete
;
6035 ------------------------------------
6036 -- Discriminant_Checks_Suppressed --
6037 ------------------------------------
6039 function Discriminant_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
6042 if Is_Unchecked_Union
(E
) then
6044 elsif Checks_May_Be_Suppressed
(E
) then
6045 return Is_Check_Suppressed
(E
, Discriminant_Check
);
6049 return Scope_Suppress
.Suppress
(Discriminant_Check
);
6050 end Discriminant_Checks_Suppressed
;
6052 --------------------------------
6053 -- Division_Checks_Suppressed --
6054 --------------------------------
6056 function Division_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
6058 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
6059 return Is_Check_Suppressed
(E
, Division_Check
);
6061 return Scope_Suppress
.Suppress
(Division_Check
);
6063 end Division_Checks_Suppressed
;
6065 --------------------------------------
6066 -- Duplicated_Tag_Checks_Suppressed --
6067 --------------------------------------
6069 function Duplicated_Tag_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
6071 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
6072 return Is_Check_Suppressed
(E
, Duplicated_Tag_Check
);
6074 return Scope_Suppress
.Suppress
(Duplicated_Tag_Check
);
6076 end Duplicated_Tag_Checks_Suppressed
;
6078 -----------------------------------
6079 -- Elaboration_Checks_Suppressed --
6080 -----------------------------------
6082 function Elaboration_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
6084 -- The complication in this routine is that if we are in the dynamic
6085 -- model of elaboration, we also check All_Checks, since All_Checks
6086 -- does not set Elaboration_Check explicitly.
6089 if Kill_Elaboration_Checks
(E
) then
6092 elsif Checks_May_Be_Suppressed
(E
) then
6093 if Is_Check_Suppressed
(E
, Elaboration_Check
) then
6096 elsif Dynamic_Elaboration_Checks
then
6097 return Is_Check_Suppressed
(E
, All_Checks
);
6105 if Scope_Suppress
.Suppress
(Elaboration_Check
) then
6108 elsif Dynamic_Elaboration_Checks
then
6109 return Scope_Suppress
.Suppress
(All_Checks
);
6114 end Elaboration_Checks_Suppressed
;
6116 ---------------------------
6117 -- Enable_Overflow_Check --
6118 ---------------------------
6120 procedure Enable_Overflow_Check
(N
: Node_Id
) is
6121 Typ
: constant Entity_Id
:= Base_Type
(Etype
(N
));
6122 Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
6130 Do_Ovflow_Check
: Boolean;
6133 if Debug_Flag_CC
then
6134 w
("Enable_Overflow_Check for node ", Int
(N
));
6135 Write_Str
(" Source location = ");
6140 -- No check if overflow checks suppressed for type of node
6142 if Overflow_Checks_Suppressed
(Etype
(N
)) then
6145 -- Nothing to do for unsigned integer types, which do not overflow
6147 elsif Is_Modular_Integer_Type
(Typ
) then
6151 -- This is the point at which processing for STRICT mode diverges
6152 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
6153 -- probably more extreme that it needs to be, but what is going on here
6154 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
6155 -- to leave the processing for STRICT mode untouched. There were
6156 -- two reasons for this. First it avoided any incompatible change of
6157 -- behavior. Second, it guaranteed that STRICT mode continued to be
6160 -- The big difference is that in STRICT mode there is a fair amount of
6161 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
6162 -- know that no check is needed. We skip all that in the two new modes,
6163 -- since really overflow checking happens over a whole subtree, and we
6164 -- do the corresponding optimizations later on when applying the checks.
6166 if Mode
in Minimized_Or_Eliminated
then
6167 if not (Overflow_Checks_Suppressed
(Etype
(N
)))
6168 and then not (Is_Entity_Name
(N
)
6169 and then Overflow_Checks_Suppressed
(Entity
(N
)))
6171 Activate_Overflow_Check
(N
);
6174 if Debug_Flag_CC
then
6175 w
("Minimized/Eliminated mode");
6181 -- Remainder of processing is for STRICT case, and is unchanged from
6182 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
6184 -- Nothing to do if the range of the result is known OK. We skip this
6185 -- for conversions, since the caller already did the check, and in any
6186 -- case the condition for deleting the check for a type conversion is
6189 if Nkind
(N
) /= N_Type_Conversion
then
6190 Determine_Range
(N
, OK
, Lo
, Hi
, Assume_Valid
=> True);
6192 -- Note in the test below that we assume that the range is not OK
6193 -- if a bound of the range is equal to that of the type. That's not
6194 -- quite accurate but we do this for the following reasons:
6196 -- a) The way that Determine_Range works, it will typically report
6197 -- the bounds of the value as being equal to the bounds of the
6198 -- type, because it either can't tell anything more precise, or
6199 -- does not think it is worth the effort to be more precise.
6201 -- b) It is very unusual to have a situation in which this would
6202 -- generate an unnecessary overflow check (an example would be
6203 -- a subtype with a range 0 .. Integer'Last - 1 to which the
6204 -- literal value one is added).
6206 -- c) The alternative is a lot of special casing in this routine
6207 -- which would partially duplicate Determine_Range processing.
6210 Do_Ovflow_Check
:= True;
6212 -- Note that the following checks are quite deliberately > and <
6213 -- rather than >= and <= as explained above.
6215 if Lo
> Expr_Value
(Type_Low_Bound
(Typ
))
6217 Hi
< Expr_Value
(Type_High_Bound
(Typ
))
6219 Do_Ovflow_Check
:= False;
6221 -- Despite the comments above, it is worth dealing specially with
6222 -- division. The only case where integer division can overflow is
6223 -- (largest negative number) / (-1). So we will do an extra range
6224 -- analysis to see if this is possible.
6226 elsif Nkind
(N
) = N_Op_Divide
then
6228 (Left_Opnd
(N
), OK
, Lo
, Hi
, Assume_Valid
=> True);
6230 if OK
and then Lo
> Expr_Value
(Type_Low_Bound
(Typ
)) then
6231 Do_Ovflow_Check
:= False;
6235 (Right_Opnd
(N
), OK
, Lo
, Hi
, Assume_Valid
=> True);
6237 if OK
and then (Lo
> Uint_Minus_1
6241 Do_Ovflow_Check
:= False;
6245 -- Likewise for Abs/Minus, the only case where the operation can
6246 -- overflow is when the operand is the largest negative number.
6248 elsif Nkind
(N
) in N_Op_Abs | N_Op_Minus
then
6250 (Right_Opnd
(N
), OK
, Lo
, Hi
, Assume_Valid
=> True);
6252 if OK
and then Lo
> Expr_Value
(Type_Low_Bound
(Typ
)) then
6253 Do_Ovflow_Check
:= False;
6257 -- If no overflow check required, we are done
6259 if not Do_Ovflow_Check
then
6260 if Debug_Flag_CC
then
6261 w
("No overflow check required");
6269 -- If not in optimizing mode, set flag and we are done. We are also done
6270 -- (and just set the flag) if the type is not a discrete type, since it
6271 -- is not worth the effort to eliminate checks for other than discrete
6272 -- types. In addition, we take this same path if we have stored the
6273 -- maximum number of checks possible already (a very unlikely situation,
6274 -- but we do not want to blow up).
6276 if Optimization_Level
= 0
6277 or else not Is_Discrete_Type
(Etype
(N
))
6278 or else Num_Saved_Checks
= Saved_Checks
'Last
6280 Activate_Overflow_Check
(N
);
6282 if Debug_Flag_CC
then
6283 w
("Optimization off");
6289 -- Otherwise evaluate and check the expression
6294 Target_Type
=> Empty
,
6300 if Debug_Flag_CC
then
6301 w
("Called Find_Check");
6305 w
(" Check_Num = ", Chk
);
6306 w
(" Ent = ", Int
(Ent
));
6307 Write_Str
(" Ofs = ");
6312 -- If check is not of form to optimize, then set flag and we are done
6315 Activate_Overflow_Check
(N
);
6319 -- If check is already performed, then return without setting flag
6322 if Debug_Flag_CC
then
6323 w
("Check suppressed!");
6329 -- Here we will make a new entry for the new check
6331 Activate_Overflow_Check
(N
);
6332 Num_Saved_Checks
:= Num_Saved_Checks
+ 1;
6333 Saved_Checks
(Num_Saved_Checks
) :=
6338 Target_Type
=> Empty
);
6340 if Debug_Flag_CC
then
6341 w
("Make new entry, check number = ", Num_Saved_Checks
);
6342 w
(" Entity = ", Int
(Ent
));
6343 Write_Str
(" Offset = ");
6345 w
(" Check_Type = O");
6346 w
(" Target_Type = Empty");
6349 -- If we get an exception, then something went wrong, probably because of
6350 -- an error in the structure of the tree due to an incorrect program. Or
6351 -- it may be a bug in the optimization circuit. In either case the safest
6352 -- thing is simply to set the check flag unconditionally.
6356 Activate_Overflow_Check
(N
);
6358 if Debug_Flag_CC
then
6359 w
(" exception occurred, overflow flag set");
6363 end Enable_Overflow_Check
;
6365 ------------------------
6366 -- Enable_Range_Check --
6367 ------------------------
6369 procedure Enable_Range_Check
(N
: Node_Id
) is
6378 -- Return if unchecked type conversion with range check killed. In this
6379 -- case we never set the flag (that's what Kill_Range_Check is about).
6381 if Nkind
(N
) = N_Unchecked_Type_Conversion
6382 and then Kill_Range_Check
(N
)
6387 -- Do not set range check flag if parent is assignment statement or
6388 -- object declaration with Suppress_Assignment_Checks flag set.
6390 if Nkind
(Parent
(N
)) in N_Assignment_Statement | N_Object_Declaration
6391 and then Suppress_Assignment_Checks
(Parent
(N
))
6396 -- Check for various cases where we should suppress the range check
6398 -- No check if range checks suppressed for type of node
6400 if Present
(Etype
(N
)) and then Range_Checks_Suppressed
(Etype
(N
)) then
6403 -- No check if node is an entity name, and range checks are suppressed
6404 -- for this entity, or for the type of this entity.
6406 elsif Is_Entity_Name
(N
)
6407 and then (Range_Checks_Suppressed
(Entity
(N
))
6408 or else Range_Checks_Suppressed
(Etype
(Entity
(N
))))
6412 -- No checks if index of array, and index checks are suppressed for
6413 -- the array object or the type of the array.
6415 elsif Nkind
(Parent
(N
)) = N_Indexed_Component
then
6417 Pref
: constant Node_Id
:= Prefix
(Parent
(N
));
6419 if Is_Entity_Name
(Pref
)
6420 and then Index_Checks_Suppressed
(Entity
(Pref
))
6423 elsif Index_Checks_Suppressed
(Etype
(Pref
)) then
6429 -- Debug trace output
6431 if Debug_Flag_CC
then
6432 w
("Enable_Range_Check for node ", Int
(N
));
6433 Write_Str
(" Source location = ");
6438 -- If not in optimizing mode, set flag and we are done. We are also done
6439 -- (and just set the flag) if the type is not a discrete type, since it
6440 -- is not worth the effort to eliminate checks for other than discrete
6441 -- types. In addition, we take this same path if we have stored the
6442 -- maximum number of checks possible already (a very unlikely situation,
6443 -- but we do not want to blow up).
6445 if Optimization_Level
= 0
6446 or else No
(Etype
(N
))
6447 or else not Is_Discrete_Type
(Etype
(N
))
6448 or else Num_Saved_Checks
= Saved_Checks
'Last
6450 Activate_Range_Check
(N
);
6452 if Debug_Flag_CC
then
6453 w
("Optimization off");
6459 -- Otherwise find out the target type
6463 -- For assignment, use left side subtype
6465 if Nkind
(P
) = N_Assignment_Statement
6466 and then Expression
(P
) = N
6468 Ttyp
:= Etype
(Name
(P
));
6470 -- For indexed component, use subscript subtype
6472 elsif Nkind
(P
) = N_Indexed_Component
then
6479 Atyp
:= Etype
(Prefix
(P
));
6481 if Is_Access_Type
(Atyp
) then
6482 Atyp
:= Designated_Type
(Atyp
);
6484 -- If the prefix is an access to an unconstrained array,
6485 -- perform check unconditionally: it depends on the bounds of
6486 -- an object and we cannot currently recognize whether the test
6487 -- may be redundant.
6489 if not Is_Constrained
(Atyp
) then
6490 Activate_Range_Check
(N
);
6494 -- Ditto if prefix is simply an unconstrained array. We used
6495 -- to think this case was OK, if the prefix was not an explicit
6496 -- dereference, but we have now seen a case where this is not
6497 -- true, so it is safer to just suppress the optimization in this
6498 -- case. The back end is getting better at eliminating redundant
6499 -- checks in any case, so the loss won't be important.
6501 elsif Is_Array_Type
(Atyp
)
6502 and then not Is_Constrained
(Atyp
)
6504 Activate_Range_Check
(N
);
6508 Indx
:= First_Index
(Atyp
);
6509 Subs
:= First
(Expressions
(P
));
6512 Ttyp
:= Etype
(Indx
);
6521 -- For now, ignore all other cases, they are not so interesting
6524 if Debug_Flag_CC
then
6525 w
(" target type not found, flag set");
6528 Activate_Range_Check
(N
);
6532 -- Evaluate and check the expression
6537 Target_Type
=> Ttyp
,
6543 if Debug_Flag_CC
then
6544 w
("Called Find_Check");
6545 w
("Target_Typ = ", Int
(Ttyp
));
6549 w
(" Check_Num = ", Chk
);
6550 w
(" Ent = ", Int
(Ent
));
6551 Write_Str
(" Ofs = ");
6556 -- If check is not of form to optimize, then set flag and we are done
6559 if Debug_Flag_CC
then
6560 w
(" expression not of optimizable type, flag set");
6563 Activate_Range_Check
(N
);
6567 -- If check is already performed, then return without setting flag
6570 if Debug_Flag_CC
then
6571 w
("Check suppressed!");
6577 -- Here we will make a new entry for the new check
6579 Activate_Range_Check
(N
);
6580 Num_Saved_Checks
:= Num_Saved_Checks
+ 1;
6581 Saved_Checks
(Num_Saved_Checks
) :=
6586 Target_Type
=> Ttyp
);
6588 if Debug_Flag_CC
then
6589 w
("Make new entry, check number = ", Num_Saved_Checks
);
6590 w
(" Entity = ", Int
(Ent
));
6591 Write_Str
(" Offset = ");
6593 w
(" Check_Type = R");
6594 w
(" Target_Type = ", Int
(Ttyp
));
6595 pg
(Union_Id
(Ttyp
));
6598 -- If we get an exception, then something went wrong, probably because of
6599 -- an error in the structure of the tree due to an incorrect program. Or
6600 -- it may be a bug in the optimization circuit. In either case the safest
6601 -- thing is simply to set the check flag unconditionally.
6605 Activate_Range_Check
(N
);
6607 if Debug_Flag_CC
then
6608 w
(" exception occurred, range flag set");
6612 end Enable_Range_Check
;
6618 procedure Ensure_Valid
6620 Holes_OK
: Boolean := False;
6621 Related_Id
: Entity_Id
:= Empty
;
6622 Is_Low_Bound
: Boolean := False;
6623 Is_High_Bound
: Boolean := False)
6625 Typ
: constant Entity_Id
:= Etype
(Expr
);
6628 -- Ignore call if we are not doing any validity checking
6630 if not Validity_Checks_On
then
6633 -- Ignore call if range or validity checks suppressed on entity or type
6635 elsif Range_Or_Validity_Checks_Suppressed
(Expr
) then
6638 -- No check required if expression is from the expander, we assume the
6639 -- expander will generate whatever checks are needed. Note that this is
6640 -- not just an optimization, it avoids infinite recursions.
6642 -- Unchecked conversions must be checked, unless they are initialized
6643 -- scalar values, as in a component assignment in an init proc.
6645 -- In addition, we force a check if Force_Validity_Checks is set
6647 elsif not Comes_From_Source
(Expr
)
6649 (Nkind
(Expr
) = N_Identifier
6650 and then Present
(Renamed_Entity_Or_Object
(Entity
(Expr
)))
6652 Comes_From_Source
(Renamed_Entity_Or_Object
(Entity
(Expr
))))
6653 and then not Force_Validity_Checks
6654 and then (Nkind
(Expr
) /= N_Unchecked_Type_Conversion
6655 or else Kill_Range_Check
(Expr
))
6659 -- No check required if expression is known to have valid value
6661 elsif Expr_Known_Valid
(Expr
) then
6664 -- No check needed within a generated predicate function. Validity
6665 -- of input value will have been checked earlier.
6667 elsif Ekind
(Current_Scope
) = E_Function
6668 and then Is_Predicate_Function
(Current_Scope
)
6672 -- Ignore case of enumeration with holes where the flag is set not to
6673 -- worry about holes, since no special validity check is needed
6675 elsif Is_Enumeration_Type
(Typ
)
6676 and then Has_Non_Standard_Rep
(Typ
)
6681 -- No check required on the left-hand side of an assignment
6683 elsif Nkind
(Parent
(Expr
)) = N_Assignment_Statement
6684 and then Expr
= Name
(Parent
(Expr
))
6688 -- No check on a universal real constant. The context will eventually
6689 -- convert it to a machine number for some target type, or report an
6692 elsif Nkind
(Expr
) = N_Real_Literal
6693 and then Etype
(Expr
) = Universal_Real
6697 -- If the expression denotes a component of a packed boolean array,
6698 -- no possible check applies. We ignore the old ACATS chestnuts that
6699 -- involve Boolean range True..True.
6701 -- Note: validity checks are generated for expressions that yield a
6702 -- scalar type, when it is possible to create a value that is outside of
6703 -- the type. If this is a one-bit boolean no such value exists. This is
6704 -- an optimization, and it also prevents compiler blowing up during the
6705 -- elaboration of improperly expanded packed array references.
6707 elsif Nkind
(Expr
) = N_Indexed_Component
6708 and then Is_Bit_Packed_Array
(Etype
(Prefix
(Expr
)))
6709 and then Root_Type
(Etype
(Expr
)) = Standard_Boolean
6713 -- For an expression with actions, we want to insert the validity check
6714 -- on the final Expression.
6716 elsif Nkind
(Expr
) = N_Expression_With_Actions
then
6717 Ensure_Valid
(Expression
(Expr
));
6720 -- An annoying special case. If this is an out parameter of a scalar
6721 -- type, then the value is not going to be accessed, therefore it is
6722 -- inappropriate to do any validity check at the call site. Likewise
6723 -- if the parameter is passed by reference.
6726 -- Only need to worry about scalar types
6728 if Is_Scalar_Type
(Typ
) then
6738 -- Find actual argument (which may be a parameter association)
6739 -- and the parent of the actual argument (the call statement)
6744 if Nkind
(P
) = N_Parameter_Association
then
6749 -- If this is an indirect or dispatching call, get signature
6750 -- from the subprogram type.
6752 if Nkind
(P
) in N_Entry_Call_Statement
6754 | N_Procedure_Call_Statement
6756 E
:= Get_Called_Entity
(P
);
6757 L
:= Parameter_Associations
(P
);
6759 -- Only need to worry if there are indeed actuals, and if
6760 -- this could be a subprogram call, otherwise we cannot get
6761 -- a match (either we are not an argument, or the mode of
6762 -- the formal is not OUT). This test also filters out the
6765 if Is_Non_Empty_List
(L
) and then Is_Subprogram
(E
) then
6767 -- This is the loop through parameters, looking for an
6768 -- OUT parameter for which we are the argument.
6770 F
:= First_Formal
(E
);
6772 while Present
(F
) loop
6774 and then (Ekind
(F
) = E_Out_Parameter
6775 or else Mechanism
(F
) = By_Reference
)
6789 -- If this is a boolean expression, only its elementary operands need
6790 -- checking: if they are valid, a boolean or short-circuit operation
6791 -- with them will be valid as well.
6793 if Base_Type
(Typ
) = Standard_Boolean
6795 (Nkind
(Expr
) in N_Op
or else Nkind
(Expr
) in N_Short_Circuit
)
6800 -- If we fall through, a validity check is required
6802 Insert_Valid_Check
(Expr
, Related_Id
, Is_Low_Bound
, Is_High_Bound
);
6804 if Is_Entity_Name
(Expr
)
6805 and then Safe_To_Capture_Value
(Expr
, Entity
(Expr
))
6807 Set_Is_Known_Valid
(Entity
(Expr
));
6811 ----------------------
6812 -- Expr_Known_Valid --
6813 ----------------------
6815 function Expr_Known_Valid
(Expr
: Node_Id
) return Boolean is
6816 Typ
: constant Entity_Id
:= Etype
(Expr
);
6819 -- Non-scalar types are always considered valid, since they never give
6820 -- rise to the issues of erroneous or bounded error behavior that are
6821 -- the concern. In formal reference manual terms the notion of validity
6822 -- only applies to scalar types. Note that even when packed arrays are
6823 -- represented using modular types, they are still arrays semantically,
6824 -- so they are also always valid (in particular, the unused bits can be
6825 -- random rubbish without affecting the validity of the array value).
6827 if not Is_Scalar_Type
(Typ
) or else Is_Packed_Array_Impl_Type
(Typ
) then
6830 -- If no validity checking, then everything is considered valid
6832 elsif not Validity_Checks_On
then
6835 -- Floating-point types are considered valid unless floating-point
6836 -- validity checks have been specifically turned on.
6838 elsif Is_Floating_Point_Type
(Typ
)
6839 and then not Validity_Check_Floating_Point
6843 elsif Is_Static_Expression
(Expr
) then
6846 -- If the expression is the value of an object that is known to be
6847 -- valid, then clearly the expression value itself is valid.
6849 elsif Is_Entity_Name
(Expr
)
6850 and then Is_Known_Valid
(Entity
(Expr
))
6852 -- Exclude volatile variables
6854 and then not Treat_As_Volatile
(Entity
(Expr
))
6858 -- References to discriminants are always considered valid. The value
6859 -- of a discriminant gets checked when the object is built. Within the
6860 -- record, we consider it valid, and it is important to do so, since
6861 -- otherwise we can try to generate bogus validity checks which
6862 -- reference discriminants out of scope. Discriminants of concurrent
6863 -- types are excluded for the same reason.
6865 elsif Is_Entity_Name
(Expr
)
6866 and then Denotes_Discriminant
(Expr
, Check_Concurrent
=> True)
6870 -- If the type is one for which all values are known valid, then we are
6871 -- sure that the value is valid except in the slightly odd case where
6872 -- the expression is a reference to a variable whose size has been
6873 -- explicitly set to a value greater than the object size.
6875 elsif Is_Known_Valid
(Typ
) then
6876 if Is_Entity_Name
(Expr
)
6877 and then Ekind
(Entity
(Expr
)) = E_Variable
6878 and then Known_Esize
(Entity
(Expr
))
6879 and then Esize
(Entity
(Expr
)) > Esize
(Typ
)
6886 -- Integer and character literals always have valid values, where
6887 -- appropriate these will be range checked in any case.
6889 elsif Nkind
(Expr
) in N_Integer_Literal | N_Character_Literal
then
6892 -- If we have a type conversion or a qualification of a known valid
6893 -- value, then the result will always be valid.
6895 elsif Nkind
(Expr
) in N_Type_Conversion | N_Qualified_Expression
then
6896 return Expr_Known_Valid
(Expression
(Expr
));
6898 -- Case of expression is a non-floating-point operator. In this case we
6899 -- can assume the result is valid the generated code for the operator
6900 -- will include whatever checks are needed (e.g. range checks) to ensure
6901 -- validity. This assumption does not hold for the floating-point case,
6902 -- since floating-point operators can generate Infinite or NaN results
6903 -- which are considered invalid.
6905 -- Historical note: in older versions, the exemption of floating-point
6906 -- types from this assumption was done only in cases where the parent
6907 -- was an assignment, function call or parameter association. Presumably
6908 -- the idea was that in other contexts, the result would be checked
6909 -- elsewhere, but this list of cases was missing tests (at least the
6910 -- N_Object_Declaration case, as shown by a reported missing validity
6911 -- check), and it is not clear why function calls but not procedure
6912 -- calls were tested for. It really seems more accurate and much
6913 -- safer to recognize that expressions which are the result of a
6914 -- floating-point operator can never be assumed to be valid.
6916 elsif Nkind
(Expr
) in N_Op
and then not Is_Floating_Point_Type
(Typ
) then
6919 -- The result of a membership test is always valid, since it is true or
6920 -- false, there are no other possibilities.
6922 elsif Nkind
(Expr
) in N_Membership_Test
then
6925 -- For all other cases, we do not know the expression is valid
6930 end Expr_Known_Valid
;
6936 procedure Find_Check
6938 Check_Type
: Character;
6939 Target_Type
: Entity_Id
;
6940 Entry_OK
: out Boolean;
6941 Check_Num
: out Nat
;
6942 Ent
: out Entity_Id
;
6945 function Within_Range_Of
6946 (Target_Type
: Entity_Id
;
6947 Check_Type
: Entity_Id
) return Boolean;
6948 -- Given a requirement for checking a range against Target_Type, and
6949 -- and a range Check_Type against which a check has already been made,
6950 -- determines if the check against check type is sufficient to ensure
6951 -- that no check against Target_Type is required.
6953 ---------------------
6954 -- Within_Range_Of --
6955 ---------------------
6957 function Within_Range_Of
6958 (Target_Type
: Entity_Id
;
6959 Check_Type
: Entity_Id
) return Boolean
6962 if Target_Type
= Check_Type
then
6967 Tlo
: constant Node_Id
:= Type_Low_Bound
(Target_Type
);
6968 Thi
: constant Node_Id
:= Type_High_Bound
(Target_Type
);
6969 Clo
: constant Node_Id
:= Type_Low_Bound
(Check_Type
);
6970 Chi
: constant Node_Id
:= Type_High_Bound
(Check_Type
);
6974 or else (Compile_Time_Known_Value
(Tlo
)
6976 Compile_Time_Known_Value
(Clo
)
6978 Expr_Value
(Clo
) >= Expr_Value
(Tlo
)))
6981 or else (Compile_Time_Known_Value
(Thi
)
6983 Compile_Time_Known_Value
(Chi
)
6985 Expr_Value
(Chi
) <= Expr_Value
(Clo
)))
6993 end Within_Range_Of
;
6995 -- Start of processing for Find_Check
6998 -- Establish default, in case no entry is found
7002 -- Case of expression is simple entity reference
7004 if Is_Entity_Name
(Expr
) then
7005 Ent
:= Entity
(Expr
);
7008 -- Case of expression is entity + known constant
7010 elsif Nkind
(Expr
) = N_Op_Add
7011 and then Compile_Time_Known_Value
(Right_Opnd
(Expr
))
7012 and then Is_Entity_Name
(Left_Opnd
(Expr
))
7014 Ent
:= Entity
(Left_Opnd
(Expr
));
7015 Ofs
:= Expr_Value
(Right_Opnd
(Expr
));
7017 -- Case of expression is entity - known constant
7019 elsif Nkind
(Expr
) = N_Op_Subtract
7020 and then Compile_Time_Known_Value
(Right_Opnd
(Expr
))
7021 and then Is_Entity_Name
(Left_Opnd
(Expr
))
7023 Ent
:= Entity
(Left_Opnd
(Expr
));
7024 Ofs
:= UI_Negate
(Expr_Value
(Right_Opnd
(Expr
)));
7026 -- Any other expression is not of the right form
7035 -- Come here with expression of appropriate form, check if entity is an
7036 -- appropriate one for our purposes.
7038 if (Ekind
(Ent
) = E_Variable
7039 or else Is_Constant_Object
(Ent
))
7040 and then not Is_Library_Level_Entity
(Ent
)
7048 -- See if there is matching check already
7050 for J
in reverse 1 .. Num_Saved_Checks
loop
7052 SC
: Saved_Check
renames Saved_Checks
(J
);
7054 if SC
.Killed
= False
7055 and then SC
.Entity
= Ent
7056 and then SC
.Offset
= Ofs
7057 and then SC
.Check_Type
= Check_Type
7058 and then Within_Range_Of
(Target_Type
, SC
.Target_Type
)
7066 -- If we fall through entry was not found
7071 ---------------------------------
7072 -- Generate_Discriminant_Check --
7073 ---------------------------------
7075 procedure Generate_Discriminant_Check
(N
: Node_Id
) is
7076 Loc
: constant Source_Ptr
:= Sloc
(N
);
7077 Pref
: constant Node_Id
:= Prefix
(N
);
7078 Sel
: constant Node_Id
:= Selector_Name
(N
);
7080 Orig_Comp
: constant Entity_Id
:=
7081 Original_Record_Component
(Entity
(Sel
));
7082 -- The original component to be checked
7084 Discr_Fct
: constant Entity_Id
:=
7085 Discriminant_Checking_Func
(Orig_Comp
);
7086 -- The discriminant checking function
7089 -- One discriminant to be checked in the type
7091 Real_Discr
: Entity_Id
;
7092 -- Actual discriminant in the call
7094 Pref_Type
: Entity_Id
;
7095 -- Type of relevant prefix (ignoring private/access stuff)
7098 -- List of arguments for function call
7101 -- Keep track of the formal corresponding to the actual we build for
7102 -- each discriminant, in order to be able to perform the necessary type
7106 -- Selected component reference for checking function argument
7109 Pref_Type
:= Etype
(Pref
);
7111 -- Force evaluation of the prefix, so that it does not get evaluated
7112 -- twice (once for the check, once for the actual reference). Such a
7113 -- double evaluation is always a potential source of inefficiency, and
7114 -- is functionally incorrect in the volatile case, or when the prefix
7115 -- may have side effects. A nonvolatile entity or a component of a
7116 -- nonvolatile entity requires no evaluation.
7118 if Is_Entity_Name
(Pref
) then
7119 if Treat_As_Volatile
(Entity
(Pref
)) then
7120 Force_Evaluation
(Pref
, Name_Req
=> True);
7123 elsif Treat_As_Volatile
(Etype
(Pref
)) then
7124 Force_Evaluation
(Pref
, Name_Req
=> True);
7126 elsif Nkind
(Pref
) = N_Selected_Component
7127 and then Is_Entity_Name
(Prefix
(Pref
))
7132 Force_Evaluation
(Pref
, Name_Req
=> True);
7135 -- For a tagged type, use the scope of the original component to
7136 -- obtain the type, because ???
7138 if Is_Tagged_Type
(Scope
(Orig_Comp
)) then
7139 Pref_Type
:= Scope
(Orig_Comp
);
7141 -- For an untagged derived type, use the discriminants of the parent
7142 -- which have been renamed in the derivation, possibly by a one-to-many
7143 -- discriminant constraint. For untagged type, initially get the Etype
7147 if Is_Derived_Type
(Pref_Type
)
7148 and then Number_Discriminants
(Pref_Type
) /=
7149 Number_Discriminants
(Etype
(Base_Type
(Pref_Type
)))
7151 Pref_Type
:= Etype
(Base_Type
(Pref_Type
));
7155 -- We definitely should have a checking function, This routine should
7156 -- not be called if no discriminant checking function is present.
7158 pragma Assert
(Present
(Discr_Fct
));
7160 -- Create the list of the actual parameters for the call. This list
7161 -- is the list of the discriminant fields of the record expression to
7162 -- be discriminant checked.
7165 Formal
:= First_Formal
(Discr_Fct
);
7166 Discr
:= First_Discriminant
(Pref_Type
);
7167 while Present
(Discr
) loop
7169 -- If we have a corresponding discriminant field, and a parent
7170 -- subtype is present, then we want to use the corresponding
7171 -- discriminant since this is the one with the useful value.
7173 if Present
(Corresponding_Discriminant
(Discr
))
7174 and then Ekind
(Pref_Type
) = E_Record_Type
7175 and then Present
(Parent_Subtype
(Pref_Type
))
7177 Real_Discr
:= Corresponding_Discriminant
(Discr
);
7179 Real_Discr
:= Discr
;
7182 -- Construct the reference to the discriminant
7185 Make_Selected_Component
(Loc
,
7187 Unchecked_Convert_To
(Pref_Type
,
7188 Duplicate_Subexpr
(Pref
)),
7189 Selector_Name
=> New_Occurrence_Of
(Real_Discr
, Loc
));
7191 -- Manually analyze and resolve this selected component. We really
7192 -- want it just as it appears above, and do not want the expander
7193 -- playing discriminal games etc with this reference. Then we append
7194 -- the argument to the list we are gathering.
7196 Set_Etype
(Scomp
, Etype
(Real_Discr
));
7197 Set_Analyzed
(Scomp
, True);
7198 Append_To
(Args
, Convert_To
(Etype
(Formal
), Scomp
));
7200 Next_Formal_With_Extras
(Formal
);
7201 Next_Discriminant
(Discr
);
7204 -- Now build and insert the call
7207 Make_Raise_Constraint_Error
(Loc
,
7209 Make_Function_Call
(Loc
,
7210 Name
=> New_Occurrence_Of
(Discr_Fct
, Loc
),
7211 Parameter_Associations
=> Args
),
7212 Reason
=> CE_Discriminant_Check_Failed
));
7213 end Generate_Discriminant_Check
;
7215 ---------------------------
7216 -- Generate_Index_Checks --
7217 ---------------------------
7219 procedure Generate_Index_Checks
7221 Checks_Generated
: out Dimension_Set
)
7224 function Entity_Of_Prefix
return Entity_Id
;
7225 -- Returns the entity of the prefix of N (or Empty if not found)
7227 ----------------------
7228 -- Entity_Of_Prefix --
7229 ----------------------
7231 function Entity_Of_Prefix
return Entity_Id
is
7236 while not Is_Entity_Name
(P
) loop
7237 if Nkind
(P
) not in N_Selected_Component | N_Indexed_Component
then
7245 end Entity_Of_Prefix
;
7249 Loc
: constant Source_Ptr
:= Sloc
(N
);
7250 A
: constant Node_Id
:= Prefix
(N
);
7251 A_Ent
: constant Entity_Id
:= Entity_Of_Prefix
;
7255 -- Start of processing for Generate_Index_Checks
7258 Checks_Generated
.Elements
:= (others => False);
7260 -- Ignore call if the prefix is not an array since we have a serious
7261 -- error in the sources. Ignore it also if index checks are suppressed
7262 -- for array object or type.
7264 if not Is_Array_Type
(Etype
(A
))
7265 or else (Present
(A_Ent
) and then Index_Checks_Suppressed
(A_Ent
))
7266 or else Index_Checks_Suppressed
(Etype
(A
))
7270 -- The indexed component we are dealing with contains 'Loop_Entry in its
7271 -- prefix. This case arises when analysis has determined that constructs
7274 -- Prefix'Loop_Entry (Expr)
7275 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
7277 -- require rewriting for error detection purposes. A side effect of this
7278 -- action is the generation of index checks that mention 'Loop_Entry.
7279 -- Delay the generation of the check until 'Loop_Entry has been properly
7280 -- expanded. This is done in Expand_Loop_Entry_Attributes.
7282 elsif Nkind
(Prefix
(N
)) = N_Attribute_Reference
7283 and then Attribute_Name
(Prefix
(N
)) = Name_Loop_Entry
7288 -- Generate a raise of constraint error with the appropriate reason and
7289 -- a condition of the form:
7291 -- Base_Type (Sub) not in Array'Range (Subscript)
7293 -- Note that the reason we generate the conversion to the base type here
7294 -- is that we definitely want the range check to take place, even if it
7295 -- looks like the subtype is OK. Optimization considerations that allow
7296 -- us to omit the check have already been taken into account in the
7297 -- setting of the Do_Range_Check flag earlier on.
7299 Expr
:= First
(Expressions
(N
));
7301 -- Handle string literals
7303 if Ekind
(Etype
(A
)) = E_String_Literal_Subtype
then
7304 if Do_Range_Check
(Expr
) then
7305 Set_Do_Range_Check
(Expr
, False);
7307 -- For string literals we obtain the bounds of the string from the
7308 -- associated subtype.
7311 Make_Raise_Constraint_Error
(Loc
,
7315 Convert_To
(Base_Type
(Etype
(Expr
)),
7316 Duplicate_Subexpr_Move_Checks
(Expr
)),
7318 Make_Attribute_Reference
(Loc
,
7319 Prefix
=> New_Occurrence_Of
(Etype
(A
), Loc
),
7320 Attribute_Name
=> Name_Range
)),
7321 Reason
=> CE_Index_Check_Failed
));
7323 Checks_Generated
.Elements
(1) := True;
7339 A_Idx
:= First_Index
(Etype
(A
));
7341 while Present
(Expr
) loop
7342 if Nkind
(Expr
) = N_Expression_With_Actions
then
7343 Sub
:= Expression
(Expr
);
7348 if Do_Range_Check
(Sub
) then
7349 Set_Do_Range_Check
(Sub
, False);
7351 -- Force evaluation except for the case of a simple name of
7352 -- a nonvolatile entity.
7354 if not Is_Entity_Name
(Sub
)
7355 or else Treat_As_Volatile
(Entity
(Sub
))
7357 Force_Evaluation
(Sub
);
7360 if Nkind
(A_Idx
) = N_Range
then
7363 elsif Nkind
(A_Idx
) in N_Identifier | N_Expanded_Name
then
7364 A_Range
:= Scalar_Range
(Entity
(A_Idx
));
7366 if Nkind
(A_Range
) = N_Subtype_Indication
then
7367 A_Range
:= Range_Expression
(Constraint
(A_Range
));
7370 else pragma Assert
(Nkind
(A_Idx
) = N_Subtype_Indication
);
7371 A_Range
:= Range_Expression
(Constraint
(A_Idx
));
7374 -- For array objects with constant bounds we can generate
7375 -- the index check using the bounds of the type of the index
7378 and then Ekind
(A_Ent
) = E_Variable
7379 and then Is_Constant_Bound
(Low_Bound
(A_Range
))
7380 and then Is_Constant_Bound
(High_Bound
(A_Range
))
7383 Make_Attribute_Reference
(Loc
,
7385 New_Occurrence_Of
(Etype
(A_Idx
), Loc
),
7386 Attribute_Name
=> Name_Range
);
7388 -- For arrays with non-constant bounds we cannot generate
7389 -- the index check using the bounds of the type of the index
7390 -- since it may reference discriminants of some enclosing
7391 -- type. We obtain the bounds directly from the prefix
7398 Num
:= New_List
(Make_Integer_Literal
(Loc
, Ind
));
7402 Make_Attribute_Reference
(Loc
,
7404 Duplicate_Subexpr_Move_Checks
(A
, Name_Req
=> True),
7405 Attribute_Name
=> Name_Range
,
7406 Expressions
=> Num
);
7410 Make_Raise_Constraint_Error
(Loc
,
7414 Convert_To
(Base_Type
(Etype
(Sub
)),
7415 Duplicate_Subexpr_Move_Checks
(Sub
)),
7416 Right_Opnd
=> Range_N
),
7417 Reason
=> CE_Index_Check_Failed
);
7419 if Nkind
(Expr
) = N_Expression_With_Actions
then
7420 Append_To
(Actions
(Expr
), Stmt
);
7423 Insert_Action
(Expr
, Stmt
);
7426 Checks_Generated
.Elements
(Ind
) := True;
7435 end Generate_Index_Checks
;
7437 --------------------------
7438 -- Generate_Range_Check --
7439 --------------------------
7441 procedure Generate_Range_Check
7443 Target_Type
: Entity_Id
;
7444 Reason
: RT_Exception_Code
)
7446 Loc
: constant Source_Ptr
:= Sloc
(N
);
7447 Source_Type
: constant Entity_Id
:= Etype
(N
);
7448 Source_Base_Type
: constant Entity_Id
:= Base_Type
(Source_Type
);
7449 Target_Base_Type
: constant Entity_Id
:= Base_Type
(Target_Type
);
7451 procedure Convert_And_Check_Range
(Suppress
: Check_Id
);
7452 -- Convert N to the target base type and save the result in a temporary.
7453 -- The action is analyzed using the default checks as modified by the
7454 -- given Suppress argument. Then check the converted value against the
7455 -- range of the target subtype.
7457 function Is_Single_Attribute_Reference
(N
: Node_Id
) return Boolean;
7458 -- Return True if N is an expression that contains a single attribute
7459 -- reference, possibly as operand among only integer literal operands.
7461 -----------------------------
7462 -- Convert_And_Check_Range --
7463 -----------------------------
7465 procedure Convert_And_Check_Range
(Suppress
: Check_Id
) is
7466 Tnn
: constant Entity_Id
:= Make_Temporary
(Loc
, 'T', N
);
7470 -- For enumeration types with non-standard representation this is a
7471 -- direct conversion from the enumeration type to the target integer
7472 -- type, which is treated by the back end as a normal integer type
7473 -- conversion, treating the enumeration type as an integer, which is
7474 -- exactly what we want. We set Conversion_OK to make sure that the
7475 -- analyzer does not complain about what otherwise might be an
7476 -- illegal conversion.
7478 if Is_Enumeration_Type
(Source_Base_Type
)
7479 and then Present
(Enum_Pos_To_Rep
(Source_Base_Type
))
7480 and then Is_Integer_Type
(Target_Base_Type
)
7482 Conv_N
:= OK_Convert_To
(Target_Base_Type
, Duplicate_Subexpr
(N
));
7484 Conv_N
:= Convert_To
(Target_Base_Type
, Duplicate_Subexpr
(N
));
7487 -- We make a temporary to hold the value of the conversion to the
7488 -- target base type, and then do the test against this temporary.
7489 -- N itself is replaced by an occurrence of Tnn and followed by
7490 -- the explicit range check.
7492 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
7493 -- [constraint_error when Tnn not in Target_Type]
7496 Insert_Actions
(N
, New_List
(
7497 Make_Object_Declaration
(Loc
,
7498 Defining_Identifier
=> Tnn
,
7499 Object_Definition
=> New_Occurrence_Of
(Target_Base_Type
, Loc
),
7500 Constant_Present
=> True,
7501 Expression
=> Conv_N
),
7503 Make_Raise_Constraint_Error
(Loc
,
7506 Left_Opnd
=> New_Occurrence_Of
(Tnn
, Loc
),
7507 Right_Opnd
=> New_Occurrence_Of
(Target_Type
, Loc
)),
7509 Suppress
=> Suppress
);
7511 Rewrite
(N
, New_Occurrence_Of
(Tnn
, Loc
));
7513 -- Set the type of N, because the declaration for Tnn might not
7514 -- be analyzed yet, as is the case if N appears within a record
7515 -- declaration, as a discriminant constraint or expression.
7517 Set_Etype
(N
, Target_Base_Type
);
7518 end Convert_And_Check_Range
;
7520 -------------------------------------
7521 -- Is_Single_Attribute_Reference --
7522 -------------------------------------
7524 function Is_Single_Attribute_Reference
(N
: Node_Id
) return Boolean is
7526 if Nkind
(N
) = N_Attribute_Reference
then
7529 elsif Nkind
(N
) in N_Binary_Op
then
7530 if Nkind
(Right_Opnd
(N
)) = N_Integer_Literal
then
7531 return Is_Single_Attribute_Reference
(Left_Opnd
(N
));
7533 elsif Nkind
(Left_Opnd
(N
)) = N_Integer_Literal
then
7534 return Is_Single_Attribute_Reference
(Right_Opnd
(N
));
7543 end Is_Single_Attribute_Reference
;
7545 -- Start of processing for Generate_Range_Check
7548 -- First special case, if the source type is already within the range
7549 -- of the target type, then no check is needed (probably we should have
7550 -- stopped Do_Range_Check from being set in the first place, but better
7551 -- late than never in preventing junk code and junk flag settings).
7553 if In_Subrange_Of
(Source_Type
, Target_Type
)
7555 -- We do NOT apply this if the source node is a literal, since in this
7556 -- case the literal has already been labeled as having the subtype of
7561 N_Integer_Literal | N_Real_Literal | N_Character_Literal
7564 and then Ekind
(Entity
(N
)) = E_Enumeration_Literal
))
7566 Set_Do_Range_Check
(N
, False);
7570 -- Here a check is needed. If the expander is not active (which is also
7571 -- the case in GNATprove mode), then simply set the Do_Range_Check flag
7572 -- and we are done. We just want to see the range check flag set, we do
7573 -- not want to generate the explicit range check code.
7575 if not Expander_Active
then
7576 Set_Do_Range_Check
(N
);
7580 -- Here we will generate an explicit range check, so we don't want to
7581 -- set the Do_Range check flag, since the range check is taken care of
7582 -- by the code we will generate.
7584 Set_Do_Range_Check
(N
, False);
7586 -- Force evaluation of the node, so that it does not get evaluated twice
7587 -- (once for the check, once for the actual reference). Such a double
7588 -- evaluation is always a potential source of inefficiency, and is
7589 -- functionally incorrect in the volatile case.
7591 -- We skip the evaluation of attribute references because, after these
7592 -- runtime checks are generated, the expander may need to rewrite this
7593 -- node (for example, see Attribute_Max_Size_In_Storage_Elements in
7594 -- Expand_N_Attribute_Reference) and, in many cases, their return type
7595 -- is universal integer, which is a very large type for a temporary.
7597 if not Is_Single_Attribute_Reference
(N
)
7598 and then (not Is_Entity_Name
(N
)
7599 or else Treat_As_Volatile
(Entity
(N
)))
7601 Force_Evaluation
(N
, Mode
=> Strict
);
7604 -- The easiest case is when Source_Base_Type and Target_Base_Type are
7605 -- the same since in this case we can simply do a direct check of the
7606 -- value of N against the bounds of Target_Type.
7608 -- [constraint_error when N not in Target_Type]
7610 -- Note: this is by far the most common case, for example all cases of
7611 -- checks on the RHS of assignments are in this category, but not all
7612 -- cases are like this. Notably conversions can involve two types.
7614 if Source_Base_Type
= Target_Base_Type
then
7616 -- Insert the explicit range check. Note that we suppress checks for
7617 -- this code, since we don't want a recursive range check popping up.
7620 Make_Raise_Constraint_Error
(Loc
,
7623 Left_Opnd
=> Duplicate_Subexpr
(N
),
7624 Right_Opnd
=> New_Occurrence_Of
(Target_Type
, Loc
)),
7626 Suppress
=> All_Checks
);
7628 -- Next test for the case where the target type is within the bounds
7629 -- of the base type of the source type, since in this case we can
7630 -- simply convert the bounds of the target type to this base type
7633 -- [constraint_error when N not in
7634 -- Source_Base_Type (Target_Type'First)
7636 -- Source_Base_Type(Target_Type'Last))]
7638 -- The conversions will always work and need no check
7640 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
7641 -- of converting from an enumeration value to an integer type, such as
7642 -- occurs for the case of generating a range check on Enum'Val(Exp)
7643 -- (which used to be handled by gigi). This is OK, since the conversion
7644 -- itself does not require a check.
7646 elsif In_Subrange_Of
(Target_Type
, Source_Base_Type
) then
7648 -- Insert the explicit range check. Note that we suppress checks for
7649 -- this code, since we don't want a recursive range check popping up.
7651 if Is_Discrete_Type
(Source_Base_Type
)
7653 Is_Discrete_Type
(Target_Base_Type
)
7656 Make_Raise_Constraint_Error
(Loc
,
7659 Left_Opnd
=> Duplicate_Subexpr
(N
),
7664 Unchecked_Convert_To
(Source_Base_Type
,
7665 Make_Attribute_Reference
(Loc
,
7667 New_Occurrence_Of
(Target_Type
, Loc
),
7668 Attribute_Name
=> Name_First
)),
7671 Unchecked_Convert_To
(Source_Base_Type
,
7672 Make_Attribute_Reference
(Loc
,
7674 New_Occurrence_Of
(Target_Type
, Loc
),
7675 Attribute_Name
=> Name_Last
)))),
7677 Suppress
=> All_Checks
);
7679 -- For conversions involving at least one type that is not discrete,
7680 -- first convert to the target base type and then generate the range
7681 -- check. This avoids problems with values that are close to a bound
7682 -- of the target type that would fail a range check when done in a
7683 -- larger source type before converting but pass if converted with
7684 -- rounding and then checked (such as in float-to-float conversions).
7686 -- Note that overflow checks are not suppressed for this code because
7687 -- we do not know whether the source type is in range of the target
7688 -- base type (unlike in the next case below).
7691 Convert_And_Check_Range
(Suppress
=> Range_Check
);
7694 -- Note that at this stage we know that the Target_Base_Type is not in
7695 -- the range of the Source_Base_Type (since even the Target_Type itself
7696 -- is not in this range). It could still be the case that Source_Type is
7697 -- in range of the target base type since we have not checked that case.
7699 -- If that is the case, we can freely convert the source to the target,
7700 -- and then test the target result against the bounds. Note that checks
7701 -- are suppressed for this code, since we don't want a recursive range
7702 -- check popping up.
7704 elsif In_Subrange_Of
(Source_Type
, Target_Base_Type
) then
7705 Convert_And_Check_Range
(Suppress
=> All_Checks
);
7707 -- At this stage, we know that we have two scalar types, which are
7708 -- directly convertible, and where neither scalar type has a base
7709 -- range that is in the range of the other scalar type.
7711 -- The only way this can happen is with a signed and unsigned type.
7712 -- So test for these two cases:
7715 -- Case of the source is unsigned and the target is signed
7717 if Is_Unsigned_Type
(Source_Base_Type
)
7718 and then not Is_Unsigned_Type
(Target_Base_Type
)
7720 -- If the source is unsigned and the target is signed, then we
7721 -- know that the source is not shorter than the target (otherwise
7722 -- the source base type would be in the target base type range).
7724 -- In other words, the unsigned type is either the same size as
7725 -- the target, or it is larger. It cannot be smaller.
7728 (Esize
(Source_Base_Type
) >= Esize
(Target_Base_Type
));
7730 -- We only need to check the low bound if the low bound of the
7731 -- target type is non-negative. If the low bound of the target
7732 -- type is negative, then we know that we will fit fine.
7734 -- If the high bound of the target type is negative, then we
7735 -- know we have a constraint error, since we can't possibly
7736 -- have a negative source.
7738 -- With these two checks out of the way, we can do the check
7739 -- using the source type safely
7741 -- This is definitely the most annoying case.
7743 -- [constraint_error
7744 -- when (Target_Type'First >= 0
7746 -- N < Source_Base_Type (Target_Type'First))
7747 -- or else Target_Type'Last < 0
7748 -- or else N > Source_Base_Type (Target_Type'Last)];
7750 -- We turn off all checks since we know that the conversions
7751 -- will work fine, given the guards for negative values.
7754 Make_Raise_Constraint_Error
(Loc
,
7760 Left_Opnd
=> Make_Op_Ge
(Loc
,
7762 Make_Attribute_Reference
(Loc
,
7764 New_Occurrence_Of
(Target_Type
, Loc
),
7765 Attribute_Name
=> Name_First
),
7766 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
)),
7770 Left_Opnd
=> Duplicate_Subexpr
(N
),
7772 Convert_To
(Source_Base_Type
,
7773 Make_Attribute_Reference
(Loc
,
7775 New_Occurrence_Of
(Target_Type
, Loc
),
7776 Attribute_Name
=> Name_First
)))),
7781 Make_Attribute_Reference
(Loc
,
7782 Prefix
=> New_Occurrence_Of
(Target_Type
, Loc
),
7783 Attribute_Name
=> Name_Last
),
7784 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
))),
7788 Left_Opnd
=> Duplicate_Subexpr
(N
),
7790 Convert_To
(Source_Base_Type
,
7791 Make_Attribute_Reference
(Loc
,
7792 Prefix
=> New_Occurrence_Of
(Target_Type
, Loc
),
7793 Attribute_Name
=> Name_Last
)))),
7796 Suppress
=> All_Checks
);
7798 -- Only remaining possibility is that the source is signed and
7799 -- the target is unsigned.
7802 pragma Assert
(not Is_Unsigned_Type
(Source_Base_Type
)
7803 and then Is_Unsigned_Type
(Target_Base_Type
));
7805 -- If the source is signed and the target is unsigned, then we
7806 -- know that the target is not shorter than the source (otherwise
7807 -- the target base type would be in the source base type range).
7809 -- In other words, the unsigned type is either the same size as
7810 -- the target, or it is larger. It cannot be smaller.
7812 -- Clearly we have an error if the source value is negative since
7813 -- no unsigned type can have negative values. If the source type
7814 -- is non-negative, then the check can be done using the target
7817 -- Tnn : constant Target_Base_Type (N) := Target_Type;
7819 -- [constraint_error
7820 -- when N < 0 or else Tnn not in Target_Type];
7822 -- We turn off all checks for the conversion of N to the target
7823 -- base type, since we generate the explicit check to ensure that
7824 -- the value is non-negative
7827 Tnn
: constant Entity_Id
:= Make_Temporary
(Loc
, 'T', N
);
7830 Insert_Actions
(N
, New_List
(
7831 Make_Object_Declaration
(Loc
,
7832 Defining_Identifier
=> Tnn
,
7833 Object_Definition
=>
7834 New_Occurrence_Of
(Target_Base_Type
, Loc
),
7835 Constant_Present
=> True,
7837 Unchecked_Convert_To
7838 (Target_Base_Type
, Duplicate_Subexpr
(N
))),
7840 Make_Raise_Constraint_Error
(Loc
,
7845 Left_Opnd
=> Duplicate_Subexpr
(N
),
7846 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
)),
7850 Left_Opnd
=> New_Occurrence_Of
(Tnn
, Loc
),
7852 New_Occurrence_Of
(Target_Type
, Loc
))),
7855 Suppress
=> All_Checks
);
7857 -- Set the Etype explicitly, because Insert_Actions may have
7858 -- placed the declaration in the freeze list for an enclosing
7859 -- construct, and thus it is not analyzed yet.
7861 Set_Etype
(Tnn
, Target_Base_Type
);
7862 Rewrite
(N
, New_Occurrence_Of
(Tnn
, Loc
));
7866 end Generate_Range_Check
;
7872 function Get_Check_Id
(N
: Name_Id
) return Check_Id
is
7874 -- For standard check name, we can do a direct computation
7876 if N
in First_Check_Name
.. Last_Check_Name
then
7877 return Check_Id
(N
- (First_Check_Name
- 1));
7879 -- For non-standard names added by pragma Check_Name, search table
7882 for J
in All_Checks
+ 1 .. Check_Names
.Last
loop
7883 if Check_Names
.Table
(J
) = N
then
7889 -- No matching name found
7894 ---------------------
7895 -- Get_Discriminal --
7896 ---------------------
7898 function Get_Discriminal
(E
: Entity_Id
; Bound
: Node_Id
) return Node_Id
is
7899 Loc
: constant Source_Ptr
:= Sloc
(E
);
7904 -- The bound can be a bona fide parameter of a protected operation,
7905 -- rather than a prival encoded as an in-parameter.
7907 if No
(Discriminal_Link
(Entity
(Bound
))) then
7911 -- Climb the scope stack looking for an enclosing protected type. If
7912 -- we run out of scopes, return the bound itself.
7915 while Present
(Sc
) loop
7916 if Sc
= Standard_Standard
then
7918 elsif Ekind
(Sc
) = E_Protected_Type
then
7925 D
:= First_Discriminant
(Sc
);
7926 while Present
(D
) loop
7927 if Chars
(D
) = Chars
(Bound
) then
7928 return New_Occurrence_Of
(Discriminal
(D
), Loc
);
7931 Next_Discriminant
(D
);
7935 end Get_Discriminal
;
7937 ----------------------
7938 -- Get_Range_Checks --
7939 ----------------------
7941 function Get_Range_Checks
7943 Target_Typ
: Entity_Id
;
7944 Source_Typ
: Entity_Id
:= Empty
;
7945 Warn_Node
: Node_Id
:= Empty
) return Check_Result
7949 Selected_Range_Checks
(Expr
, Target_Typ
, Source_Typ
, Warn_Node
);
7950 end Get_Range_Checks
;
7956 function Guard_Access
7959 Expr
: Node_Id
) return Node_Id
7962 if Nkind
(Cond
) = N_Or_Else
then
7963 Set_Paren_Count
(Cond
, 1);
7966 if Nkind
(Expr
) = N_Allocator
then
7974 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Expr
),
7975 Right_Opnd
=> Make_Null
(Loc
)),
7976 Right_Opnd
=> Cond
);
7980 -----------------------------
7981 -- Index_Checks_Suppressed --
7982 -----------------------------
7984 function Index_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
7986 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
7987 return Is_Check_Suppressed
(E
, Index_Check
);
7989 return Scope_Suppress
.Suppress
(Index_Check
);
7991 end Index_Checks_Suppressed
;
7997 procedure Initialize
is
7999 for J
in Determine_Range_Cache_N
'Range loop
8000 Determine_Range_Cache_N
(J
) := Empty
;
8005 for J
in Int
range 1 .. All_Checks
loop
8006 Check_Names
.Append
(Name_Id
(Int
(First_Check_Name
) + J
- 1));
8010 -------------------------
8011 -- Insert_Range_Checks --
8012 -------------------------
8014 procedure Insert_Range_Checks
8015 (Checks
: Check_Result
;
8017 Suppress_Typ
: Entity_Id
;
8018 Static_Sloc
: Source_Ptr
;
8019 Do_Before
: Boolean := False)
8021 Checks_On
: constant Boolean :=
8022 not Index_Checks_Suppressed
(Suppress_Typ
)
8024 not Range_Checks_Suppressed
(Suppress_Typ
);
8026 Check_Node
: Node_Id
;
8029 -- For now we just return if Checks_On is false, however this should be
8030 -- enhanced to check for an always True value in the condition and to
8031 -- generate a compilation warning.
8033 if not Expander_Active
or not Checks_On
then
8037 for J
in 1 .. 2 loop
8038 exit when No
(Checks
(J
));
8040 if Nkind
(Checks
(J
)) = N_Raise_Constraint_Error
8041 and then Present
(Condition
(Checks
(J
)))
8043 Check_Node
:= Checks
(J
);
8046 Make_Raise_Constraint_Error
(Static_Sloc
,
8047 Reason
=> CE_Range_Check_Failed
);
8050 Mark_Rewrite_Insertion
(Check_Node
);
8053 Insert_Before_And_Analyze
(Node
, Check_Node
);
8055 Insert_After_And_Analyze
(Node
, Check_Node
);
8058 end Insert_Range_Checks
;
8060 ------------------------
8061 -- Insert_Valid_Check --
8062 ------------------------
8064 procedure Insert_Valid_Check
8066 Related_Id
: Entity_Id
:= Empty
;
8067 Is_Low_Bound
: Boolean := False;
8068 Is_High_Bound
: Boolean := False)
8070 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
8071 Typ
: Entity_Id
:= Etype
(Expr
);
8075 -- Do not insert if checks off, or if not checking validity or if
8076 -- expression is known to be valid.
8078 if not Validity_Checks_On
8079 or else Range_Or_Validity_Checks_Suppressed
(Expr
)
8080 or else Expr_Known_Valid
(Expr
)
8084 -- Do not insert checks within a predicate function. This will arise
8085 -- if the current unit and the predicate function are being compiled
8086 -- with validity checks enabled.
8088 elsif Present
(Predicate_Function
(Typ
))
8089 and then Current_Scope
= Predicate_Function
(Typ
)
8093 -- If the expression is a packed component of a modular type of the
8094 -- right size, the data is always valid.
8096 elsif Nkind
(Expr
) = N_Selected_Component
8097 and then Present
(Component_Clause
(Entity
(Selector_Name
(Expr
))))
8098 and then Is_Modular_Integer_Type
(Typ
)
8099 and then Modulus
(Typ
) = 2 ** Esize
(Entity
(Selector_Name
(Expr
)))
8103 -- Do not generate a validity check when inside a generic unit as this
8104 -- is an expansion activity.
8106 elsif Inside_A_Generic
then
8110 -- Entities declared in Lock_free protected types must be treated as
8111 -- volatile, and we must inhibit validity checks to prevent improper
8112 -- constant folding.
8114 if Is_Entity_Name
(Expr
)
8115 and then Is_Subprogram
(Scope
(Entity
(Expr
)))
8116 and then Present
(Protected_Subprogram
(Scope
(Entity
(Expr
))))
8117 and then Uses_Lock_Free
8118 (Scope
(Protected_Subprogram
(Scope
(Entity
(Expr
)))))
8123 -- If we have a checked conversion, then validity check applies to
8124 -- the expression inside the conversion, not the result, since if
8125 -- the expression inside is valid, then so is the conversion result.
8128 while Nkind
(Exp
) = N_Type_Conversion
loop
8129 Exp
:= Expression
(Exp
);
8133 -- Do not generate a check for a variable which already validates the
8134 -- value of an assignable object.
8136 if Is_Validation_Variable_Reference
(Exp
) then
8146 -- If the expression denotes an assignable object, capture its value
8147 -- in a variable and replace the original expression by the variable.
8148 -- This approach has several effects:
8150 -- 1) The evaluation of the object results in only one read in the
8151 -- case where the object is atomic or volatile.
8153 -- Var ... := Object; -- read
8155 -- 2) The captured value is the one verified by attribute 'Valid.
8156 -- As a result the object is not evaluated again, which would
8157 -- result in an unwanted read in the case where the object is
8158 -- atomic or volatile.
8160 -- if not Var'Valid then -- OK, no read of Object
8162 -- if not Object'Valid then -- Wrong, extra read of Object
8164 -- 3) The captured value replaces the original object reference.
8165 -- As a result the object is not evaluated again, in the same
8168 -- ... Var ... -- OK, no read of Object
8170 -- ... Object ... -- Wrong, extra read of Object
8172 -- 4) The use of a variable to capture the value of the object
8173 -- allows the propagation of any changes back to the original
8176 -- procedure Call (Val : in out ...);
8178 -- Var : ... := Object; -- read Object
8179 -- if not Var'Valid then -- validity check
8180 -- Call (Var); -- modify Var
8181 -- Object := Var; -- update Object
8183 if Is_Variable
(Exp
) then
8184 Var_Id
:= Make_Temporary
(Loc
, 'T', Exp
);
8186 -- Because we could be dealing with a transient scope which would
8187 -- cause our object declaration to remain unanalyzed we must do
8188 -- some manual decoration.
8190 Mutate_Ekind
(Var_Id
, E_Variable
);
8191 Set_Etype
(Var_Id
, Typ
);
8194 Make_Object_Declaration
(Loc
,
8195 Defining_Identifier
=> Var_Id
,
8196 Object_Definition
=> New_Occurrence_Of
(Typ
, Loc
),
8197 Expression
=> New_Copy_Tree
(Exp
)),
8198 Suppress
=> Validity_Check
);
8200 Set_Validated_Object
(Var_Id
, New_Copy_Tree
(Exp
));
8202 Rewrite
(Exp
, New_Occurrence_Of
(Var_Id
, Loc
));
8204 -- Move the Do_Range_Check flag over to the new Exp so it doesn't
8205 -- get lost and doesn't leak elsewhere.
8207 if Do_Range_Check
(Validated_Object
(Var_Id
)) then
8208 Set_Do_Range_Check
(Exp
);
8209 Set_Do_Range_Check
(Validated_Object
(Var_Id
), False);
8212 -- In case of a type conversion, an expansion of the expr may be
8213 -- needed (eg. fixed-point as actual).
8216 pragma Assert
(Nkind
(Expr
) = N_Type_Conversion
);
8217 Analyze_And_Resolve
(Expr
);
8220 PV
:= New_Occurrence_Of
(Var_Id
, Loc
);
8222 -- Otherwise the expression does not denote a variable. Force its
8223 -- evaluation by capturing its value in a constant. Generate:
8225 -- Temp : constant ... := Exp;
8230 Related_Id
=> Related_Id
,
8231 Is_Low_Bound
=> Is_Low_Bound
,
8232 Is_High_Bound
=> Is_High_Bound
);
8234 PV
:= New_Copy_Tree
(Exp
);
8237 -- A rather specialized test. If PV is an analyzed expression which
8238 -- is an indexed component of a packed array that has not been
8239 -- properly expanded, turn off its Analyzed flag to make sure it
8240 -- gets properly reexpanded. If the prefix is an access value,
8241 -- the dereference will be added later.
8243 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
8244 -- an analyze with the old parent pointer. This may point e.g. to
8245 -- a subprogram call, which deactivates this expansion.
8248 and then Nkind
(PV
) = N_Indexed_Component
8249 and then Is_Array_Type
(Etype
(Prefix
(PV
)))
8250 and then Present
(Packed_Array_Impl_Type
(Etype
(Prefix
(PV
))))
8252 Set_Analyzed
(PV
, False);
8255 -- Build the raise CE node to check for validity. We build a type
8256 -- qualification for the prefix, since it may not be of the form of
8257 -- a name, and we don't care in this context!
8260 Make_Raise_Constraint_Error
(Loc
,
8264 Make_Attribute_Reference
(Loc
,
8266 Attribute_Name
=> Name_Valid
)),
8267 Reason
=> CE_Invalid_Data
);
8269 -- Insert the validity check. Note that we do this with validity
8270 -- checks turned off, to avoid recursion, we do not want validity
8271 -- checks on the validity checking code itself.
8273 Insert_Action
(Expr
, CE
, Suppress
=> Validity_Check
);
8275 -- If the expression is a reference to an element of a bit-packed
8276 -- array, then it is rewritten as a renaming declaration. If the
8277 -- expression is an actual in a call, it has not been expanded,
8278 -- waiting for the proper point at which to do it. The same happens
8279 -- with renamings, so that we have to force the expansion now. This
8280 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
8283 if Is_Entity_Name
(Exp
)
8284 and then Nkind
(Parent
(Entity
(Exp
))) =
8285 N_Object_Renaming_Declaration
8288 Old_Exp
: constant Node_Id
:= Name
(Parent
(Entity
(Exp
)));
8290 if Nkind
(Old_Exp
) = N_Indexed_Component
8291 and then Is_Bit_Packed_Array
(Etype
(Prefix
(Old_Exp
)))
8293 Expand_Packed_Element_Reference
(Old_Exp
);
8298 end Insert_Valid_Check
;
8300 -------------------------------------
8301 -- Is_Signed_Integer_Arithmetic_Op --
8302 -------------------------------------
8304 function Is_Signed_Integer_Arithmetic_Op
(N
: Node_Id
) return Boolean is
8318 return Is_Signed_Integer_Type
(Etype
(N
));
8320 when N_Case_Expression
8323 return Is_Signed_Integer_Type
(Etype
(N
));
8328 end Is_Signed_Integer_Arithmetic_Op
;
8330 ----------------------------------
8331 -- Install_Null_Excluding_Check --
8332 ----------------------------------
8334 procedure Install_Null_Excluding_Check
(N
: Node_Id
) is
8335 Loc
: constant Source_Ptr
:= Sloc
(Parent
(N
));
8336 Typ
: constant Entity_Id
:= Etype
(N
);
8338 procedure Mark_Non_Null
;
8339 -- After installation of check, if the node in question is an entity
8340 -- name, then mark this entity as non-null if possible.
8346 procedure Mark_Non_Null
is
8348 -- Only case of interest is if node N is an entity name
8350 if Is_Entity_Name
(N
) then
8352 -- For sure, we want to clear an indication that this is known to
8353 -- be null, since if we get past this check, it definitely is not.
8355 Set_Is_Known_Null
(Entity
(N
), False);
8357 -- We can mark the entity as known to be non-null if it is safe to
8358 -- capture the value.
8360 if Safe_To_Capture_Value
(N
, Entity
(N
)) then
8361 Set_Is_Known_Non_Null
(Entity
(N
));
8366 -- Start of processing for Install_Null_Excluding_Check
8369 -- No need to add null-excluding checks when the tree may not be fully
8372 if Serious_Errors_Detected
> 0 then
8376 pragma Assert
(Is_Access_Type
(Typ
));
8378 -- No check inside a generic, check will be emitted in instance
8380 if Inside_A_Generic
then
8384 -- No check needed if known to be non-null
8386 if Known_Non_Null
(N
) then
8390 -- If known to be null, here is where we generate a compile time check
8392 if Known_Null
(N
) then
8394 -- Avoid generating warning message inside init procs. In SPARK mode
8395 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
8396 -- since it will be turned into an error in any case.
8398 if (not Inside_Init_Proc
or else SPARK_Mode
= On
)
8400 -- Do not emit the warning within a conditional expression,
8401 -- where the expression might not be evaluated, and the warning
8402 -- appear as extraneous noise.
8404 and then not Within_Case_Or_If_Expression
(N
)
8406 Apply_Compile_Time_Constraint_Error
8407 (N
, "null value not allowed here??", CE_Access_Check_Failed
);
8409 -- Remaining cases, where we silently insert the raise
8413 Make_Raise_Constraint_Error
(Loc
,
8414 Reason
=> CE_Access_Check_Failed
));
8421 -- If entity is never assigned, for sure a warning is appropriate
8423 if Is_Entity_Name
(N
) then
8424 Check_Unset_Reference
(N
);
8427 -- No check needed if checks are suppressed on the range. Note that we
8428 -- don't set Is_Known_Non_Null in this case (we could legitimately do
8429 -- so, since the program is erroneous, but we don't like to casually
8430 -- propagate such conclusions from erroneosity).
8432 if Access_Checks_Suppressed
(Typ
) then
8436 -- No check needed for access to concurrent record types generated by
8437 -- the expander. This is not just an optimization (though it does indeed
8438 -- remove junk checks). It also avoids generation of junk warnings.
8440 if Nkind
(N
) in N_Has_Chars
8441 and then Chars
(N
) = Name_uObject
8442 and then Is_Concurrent_Record_Type
8443 (Directly_Designated_Type
(Etype
(N
)))
8448 -- No check needed in interface thunks since the runtime check is
8449 -- already performed at the caller side.
8451 if Is_Thunk
(Current_Scope
) then
8455 -- In GNATprove mode, we do not apply the check
8457 if GNATprove_Mode
then
8461 -- Otherwise install access check
8464 Make_Raise_Constraint_Error
(Loc
,
8467 Left_Opnd
=> Duplicate_Subexpr_Move_Checks
(N
),
8468 Right_Opnd
=> Make_Null
(Loc
)),
8469 Reason
=> CE_Access_Check_Failed
));
8471 -- Mark the entity of N "non-null" except when assertions are enabled -
8472 -- since expansion becomes much more complicated (especially when it
8473 -- comes to contracts) due to the generation of wrappers and wholesale
8474 -- moving of declarations and statements which may happen.
8476 -- Additionally, it is assumed that extra checks will exist with
8477 -- assertions enabled so some potentially redundant checks are
8480 if not Assertions_Enabled
then
8483 end Install_Null_Excluding_Check
;
8485 -----------------------------------------
8486 -- Install_Primitive_Elaboration_Check --
8487 -----------------------------------------
8489 procedure Install_Primitive_Elaboration_Check
(Subp_Body
: Node_Id
) is
8490 function Within_Compilation_Unit_Instance
8491 (Subp_Id
: Entity_Id
) return Boolean;
8492 -- Determine whether subprogram Subp_Id appears within an instance which
8493 -- acts as a compilation unit.
8495 --------------------------------------
8496 -- Within_Compilation_Unit_Instance --
8497 --------------------------------------
8499 function Within_Compilation_Unit_Instance
8500 (Subp_Id
: Entity_Id
) return Boolean
8505 -- Examine the scope chain looking for a compilation-unit-level
8508 Pack
:= Scope
(Subp_Id
);
8509 while Present
(Pack
) and then Pack
/= Standard_Standard
loop
8510 if Ekind
(Pack
) = E_Package
8511 and then Is_Generic_Instance
(Pack
)
8512 and then Nkind
(Parent
(Unit_Declaration_Node
(Pack
))) =
8518 Pack
:= Scope
(Pack
);
8522 end Within_Compilation_Unit_Instance
;
8524 -- Local declarations
8526 Context
: constant Node_Id
:= Parent
(Subp_Body
);
8527 Loc
: constant Source_Ptr
:= Sloc
(Subp_Body
);
8528 Subp_Id
: constant Entity_Id
:= Unique_Defining_Entity
(Subp_Body
);
8529 Subp_Decl
: constant Node_Id
:= Unit_Declaration_Node
(Subp_Id
);
8532 Flag_Id
: Entity_Id
;
8535 Tag_Typ
: Entity_Id
;
8537 -- Start of processing for Install_Primitive_Elaboration_Check
8540 -- Do not generate an elaboration check in compilation modes where
8541 -- expansion is not desirable.
8543 if GNATprove_Mode
then
8546 -- Do not generate an elaboration check if all checks have been
8549 elsif Suppress_Checks
then
8552 -- Do not generate an elaboration check if the related subprogram is
8553 -- not subject to elaboration checks.
8555 elsif Elaboration_Checks_Suppressed
(Subp_Id
) then
8558 -- Do not generate an elaboration check if such code is not desirable
8560 elsif Restriction_Active
(No_Elaboration_Code
) then
8563 -- If pragma Pure or Preelaborate applies, then these elaboration checks
8564 -- cannot fail, so do not generate them.
8566 elsif In_Preelaborated_Unit
then
8569 -- Do not generate an elaboration check if exceptions cannot be used,
8570 -- caught, or propagated.
8572 elsif not Exceptions_OK
then
8575 -- Do not consider subprograms that are compilation units, because they
8576 -- cannot be the target of a dispatching call.
8578 elsif Nkind
(Context
) = N_Compilation_Unit
then
8581 -- Do not consider anything other than nonabstract library-level source
8585 (Comes_From_Source
(Subp_Id
)
8586 and then Is_Library_Level_Entity
(Subp_Id
)
8587 and then Is_Primitive
(Subp_Id
)
8588 and then not Is_Abstract_Subprogram
(Subp_Id
))
8592 -- Do not consider inlined primitives, because once the body is inlined
8593 -- the reference to the elaboration flag will be out of place and will
8594 -- result in an undefined symbol.
8596 elsif Is_Inlined
(Subp_Id
) or else Has_Pragma_Inline
(Subp_Id
) then
8599 -- Do not generate a duplicate elaboration check. This happens only in
8600 -- the case of primitives completed by an expression function, as the
8601 -- corresponding body is apparently analyzed and expanded twice.
8603 elsif Analyzed
(Subp_Body
) then
8606 -- Do not consider primitives that occur within an instance that is a
8607 -- compilation unit. Such an instance defines its spec and body out of
8608 -- order (body is first) within the tree, which causes the reference to
8609 -- the elaboration flag to appear as an undefined symbol.
8611 elsif Within_Compilation_Unit_Instance
(Subp_Id
) then
8615 Tag_Typ
:= Find_Dispatching_Type
(Subp_Id
);
8617 -- Only tagged primitives may be the target of a dispatching call
8619 if No
(Tag_Typ
) then
8622 -- Do not consider finalization-related primitives, because they may
8623 -- need to be called while elaboration is taking place.
8625 elsif Is_Controlled
(Tag_Typ
)
8626 and then (Is_Controlled_Procedure
(Subp_Id
, Name_Adjust
)
8627 or else Is_Controlled_Procedure
(Subp_Id
, Name_Finalize
)
8628 or else Is_Controlled_Procedure
(Subp_Id
, Name_Initialize
))
8633 -- Create the declaration of the elaboration flag. The name carries a
8634 -- unique counter in case of name overloading.
8637 Make_Defining_Identifier
(Loc
,
8638 Chars
=> New_External_Name
(Chars
(Subp_Id
), 'E', -1));
8639 Set_Is_Frozen
(Flag_Id
);
8641 -- Insert the declaration of the elaboration flag in front of the
8642 -- primitive spec and analyze it in the proper context.
8644 Push_Scope
(Scope
(Subp_Id
));
8647 -- E : Boolean := False;
8649 Insert_Action
(Subp_Decl
,
8650 Make_Object_Declaration
(Loc
,
8651 Defining_Identifier
=> Flag_Id
,
8652 Object_Definition
=> New_Occurrence_Of
(Standard_Boolean
, Loc
),
8653 Expression
=> New_Occurrence_Of
(Standard_False
, Loc
)));
8656 -- Prevent the compiler from optimizing the elaboration check by killing
8657 -- the current value of the flag and the associated assignment.
8659 Set_Current_Value
(Flag_Id
, Empty
);
8660 Set_Last_Assignment
(Flag_Id
, Empty
);
8662 -- Add a check at the top of the body declarations to ensure that the
8663 -- elaboration flag has been set.
8665 Decls
:= Declarations
(Subp_Body
);
8669 Set_Declarations
(Subp_Body
, Decls
);
8674 -- raise Program_Error with "access before elaboration";
8678 Make_Raise_Program_Error
(Loc
,
8681 Right_Opnd
=> New_Occurrence_Of
(Flag_Id
, Loc
)),
8682 Reason
=> PE_Access_Before_Elaboration
));
8684 Analyze
(First
(Decls
));
8686 -- Set the elaboration flag once the body has been elaborated. Insert
8687 -- the statement after the subprogram stub when the primitive body is
8690 if Nkind
(Context
) = N_Subunit
then
8691 Set_Ins
:= Corresponding_Stub
(Context
);
8693 Set_Ins
:= Subp_Body
;
8700 Make_Assignment_Statement
(Loc
,
8701 Name
=> New_Occurrence_Of
(Flag_Id
, Loc
),
8702 Expression
=> New_Occurrence_Of
(Standard_True
, Loc
));
8704 -- Mark the assignment statement as elaboration code. This allows the
8705 -- early call region mechanism (see Sem_Elab) to properly ignore such
8706 -- assignments even though they are non-preelaborable code.
8708 Set_Is_Elaboration_Code
(Set_Stmt
);
8710 Insert_After_And_Analyze
(Set_Ins
, Set_Stmt
);
8711 end Install_Primitive_Elaboration_Check
;
8713 --------------------------
8714 -- Install_Static_Check --
8715 --------------------------
8717 procedure Install_Static_Check
8718 (R_Cno
: Node_Id
; Loc
: Source_Ptr
; Reason
: RT_Exception_Code
)
8720 Stat
: constant Boolean := Is_OK_Static_Expression
(R_Cno
);
8721 Typ
: constant Entity_Id
:= Etype
(R_Cno
);
8725 Make_Raise_Constraint_Error
(Loc
,
8727 Set_Analyzed
(R_Cno
);
8728 Set_Etype
(R_Cno
, Typ
);
8729 Set_Raises_Constraint_Error
(R_Cno
);
8730 Set_Is_Static_Expression
(R_Cno
, Stat
);
8732 -- Now deal with possible local raise handling
8734 Possible_Local_Raise
(R_Cno
, Standard_Constraint_Error
);
8735 end Install_Static_Check
;
8737 -------------------------
8738 -- Is_Check_Suppressed --
8739 -------------------------
8741 function Is_Check_Suppressed
(E
: Entity_Id
; C
: Check_Id
) return Boolean is
8742 Ptr
: Suppress_Stack_Entry_Ptr
;
8745 -- First search the local entity suppress stack. We search this from the
8746 -- top of the stack down so that we get the innermost entry that applies
8747 -- to this case if there are nested entries.
8749 Ptr
:= Local_Suppress_Stack_Top
;
8750 while Ptr
/= null loop
8751 if (Ptr
.Entity
= Empty
or else Ptr
.Entity
= E
)
8752 and then (Ptr
.Check
= All_Checks
or else Ptr
.Check
= C
)
8754 return Ptr
.Suppress
;
8760 -- Now search the global entity suppress table for a matching entry.
8761 -- We also search this from the top down so that if there are multiple
8762 -- pragmas for the same entity, the last one applies (not clear what
8763 -- or whether the RM specifies this handling, but it seems reasonable).
8765 Ptr
:= Global_Suppress_Stack_Top
;
8766 while Ptr
/= null loop
8767 if (Ptr
.Entity
= Empty
or else Ptr
.Entity
= E
)
8768 and then (Ptr
.Check
= All_Checks
or else Ptr
.Check
= C
)
8770 return Ptr
.Suppress
;
8776 -- If we did not find a matching entry, then use the normal scope
8777 -- suppress value after all (actually this will be the global setting
8778 -- since it clearly was not overridden at any point). For a predefined
8779 -- check, we test the specific flag. For a user defined check, we check
8780 -- the All_Checks flag. The Overflow flag requires special handling to
8781 -- deal with the General vs Assertion case.
8783 if C
= Overflow_Check
then
8784 return Overflow_Checks_Suppressed
(Empty
);
8786 elsif C
in Predefined_Check_Id
then
8787 return Scope_Suppress
.Suppress
(C
);
8790 return Scope_Suppress
.Suppress
(All_Checks
);
8792 end Is_Check_Suppressed
;
8794 ---------------------
8795 -- Kill_All_Checks --
8796 ---------------------
8798 procedure Kill_All_Checks
is
8800 if Debug_Flag_CC
then
8801 w
("Kill_All_Checks");
8804 -- We reset the number of saved checks to zero, and also modify all
8805 -- stack entries for statement ranges to indicate that the number of
8806 -- checks at each level is now zero.
8808 Num_Saved_Checks
:= 0;
8810 -- Note: the Int'Min here avoids any possibility of J being out of
8811 -- range when called from e.g. Conditional_Statements_Begin.
8813 for J
in 1 .. Int
'Min (Saved_Checks_TOS
, Saved_Checks_Stack
'Last) loop
8814 Saved_Checks_Stack
(J
) := 0;
8816 end Kill_All_Checks
;
8822 procedure Kill_Checks
(V
: Entity_Id
) is
8824 if Debug_Flag_CC
then
8825 w
("Kill_Checks for entity", Int
(V
));
8828 for J
in 1 .. Num_Saved_Checks
loop
8829 if Saved_Checks
(J
).Entity
= V
then
8830 if Debug_Flag_CC
then
8831 w
(" Checks killed for saved check ", J
);
8834 Saved_Checks
(J
).Killed
:= True;
8839 ------------------------------
8840 -- Length_Checks_Suppressed --
8841 ------------------------------
8843 function Length_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
8845 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
8846 return Is_Check_Suppressed
(E
, Length_Check
);
8848 return Scope_Suppress
.Suppress
(Length_Check
);
8850 end Length_Checks_Suppressed
;
8852 -----------------------
8853 -- Make_Bignum_Block --
8854 -----------------------
8856 function Make_Bignum_Block
(Loc
: Source_Ptr
) return Node_Id
is
8857 M
: constant Entity_Id
:= Make_Defining_Identifier
(Loc
, Name_uM
);
8860 Make_Block_Statement
(Loc
,
8862 New_List
(Build_SS_Mark_Call
(Loc
, M
)),
8863 Handled_Statement_Sequence
=>
8864 Make_Handled_Sequence_Of_Statements
(Loc
,
8865 Statements
=> New_List
(Build_SS_Release_Call
(Loc
, M
))));
8866 end Make_Bignum_Block
;
8868 ----------------------------------
8869 -- Minimize_Eliminate_Overflows --
8870 ----------------------------------
8872 -- This is a recursive routine that is called at the top of an expression
8873 -- tree to properly process overflow checking for a whole subtree by making
8874 -- recursive calls to process operands. This processing may involve the use
8875 -- of bignum or long long integer arithmetic, which will change the types
8876 -- of operands and results. That's why we can't do this bottom up (since
8877 -- it would interfere with semantic analysis).
8879 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
8880 -- the operator expansion routines, as well as the expansion routines for
8881 -- if/case expression, do nothing (for the moment) except call the routine
8882 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8883 -- routine does nothing for non top-level nodes, so at the point where the
8884 -- call is made for the top level node, the entire expression subtree has
8885 -- not been expanded, or processed for overflow. All that has to happen as
8886 -- a result of the top level call to this routine.
8888 -- As noted above, the overflow processing works by making recursive calls
8889 -- for the operands, and figuring out what to do, based on the processing
8890 -- of these operands (e.g. if a bignum operand appears, the parent op has
8891 -- to be done in bignum mode), and the determined ranges of the operands.
8893 -- After possible rewriting of a constituent subexpression node, a call is
8894 -- made to either reexpand the node (if nothing has changed) or reanalyze
8895 -- the node (if it has been modified by the overflow check processing). The
8896 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8897 -- a recursive call into the whole overflow apparatus, an important rule
8898 -- for this call is that the overflow handling mode must be temporarily set
8901 procedure Minimize_Eliminate_Overflows
8905 Top_Level
: Boolean)
8907 Rtyp
: constant Entity_Id
:= Etype
(N
);
8908 pragma Assert
(Is_Signed_Integer_Type
(Rtyp
));
8909 -- Result type, must be a signed integer type
8911 Check_Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
8912 pragma Assert
(Check_Mode
in Minimized_Or_Eliminated
);
8914 Loc
: constant Source_Ptr
:= Sloc
(N
);
8917 -- Ranges of values for right operand (operator case)
8919 Llo
: Uint
:= No_Uint
; -- initialize to prevent warning
8920 Lhi
: Uint
:= No_Uint
; -- initialize to prevent warning
8921 -- Ranges of values for left operand (operator case)
8923 LLIB
: constant Entity_Id
:= Base_Type
(Standard_Long_Long_Integer
);
8924 -- Operands and results are of this type when we convert
8926 LLLo
: constant Uint
:= Intval
(Type_Low_Bound
(LLIB
));
8927 LLHi
: constant Uint
:= Intval
(Type_High_Bound
(LLIB
));
8928 -- Bounds of Long_Long_Integer
8930 Binary
: constant Boolean := Nkind
(N
) in N_Binary_Op
;
8931 -- Indicates binary operator case
8934 -- Used in call to Determine_Range
8936 Bignum_Operands
: Boolean;
8937 -- Set True if one or more operands is already of type Bignum, meaning
8938 -- that for sure (regardless of Top_Level setting) we are committed to
8939 -- doing the operation in Bignum mode (or in the case of a case or if
8940 -- expression, converting all the dependent expressions to Bignum).
8942 Long_Long_Integer_Operands
: Boolean;
8943 -- Set True if one or more operands is already of type Long_Long_Integer
8944 -- which means that if the result is known to be in the result type
8945 -- range, then we must convert such operands back to the result type.
8947 procedure Reanalyze
(Typ
: Entity_Id
; Suppress
: Boolean := False);
8948 -- This is called when we have modified the node and we therefore need
8949 -- to reanalyze it. It is important that we reset the mode to STRICT for
8950 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
8951 -- we would reenter this routine recursively which would not be good.
8952 -- The argument Suppress is set True if we also want to suppress
8953 -- overflow checking for the reexpansion (this is set when we know
8954 -- overflow is not possible). Typ is the type for the reanalysis.
8956 procedure Reexpand
(Suppress
: Boolean := False);
8957 -- This is like Reanalyze, but does not do the Analyze step, it only
8958 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
8959 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
8960 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
8961 -- Note that skipping reanalysis is not just an optimization, testing
8962 -- has showed up several complex cases in which reanalyzing an already
8963 -- analyzed node causes incorrect behavior.
8965 function In_Result_Range
return Boolean;
8966 -- Returns True iff Lo .. Hi are within range of the result type
8968 procedure Max
(A
: in out Uint
; B
: Uint
);
8969 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
8971 procedure Min
(A
: in out Uint
; B
: Uint
);
8972 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
8974 ---------------------
8975 -- In_Result_Range --
8976 ---------------------
8978 function In_Result_Range
return Boolean is
8980 if No
(Lo
) or else No
(Hi
) then
8983 elsif Is_OK_Static_Subtype
(Etype
(N
)) then
8984 return Lo
>= Expr_Value
(Type_Low_Bound
(Rtyp
))
8986 Hi
<= Expr_Value
(Type_High_Bound
(Rtyp
));
8989 return Lo
>= Expr_Value
(Type_Low_Bound
(Base_Type
(Rtyp
)))
8991 Hi
<= Expr_Value
(Type_High_Bound
(Base_Type
(Rtyp
)));
8993 end In_Result_Range
;
8999 procedure Max
(A
: in out Uint
; B
: Uint
) is
9001 if No
(A
) or else B
> A
then
9010 procedure Min
(A
: in out Uint
; B
: Uint
) is
9012 if No
(A
) or else B
< A
then
9021 procedure Reanalyze
(Typ
: Entity_Id
; Suppress
: Boolean := False) is
9022 Svg
: constant Overflow_Mode_Type
:=
9023 Scope_Suppress
.Overflow_Mode_General
;
9024 Sva
: constant Overflow_Mode_Type
:=
9025 Scope_Suppress
.Overflow_Mode_Assertions
;
9026 Svo
: constant Boolean :=
9027 Scope_Suppress
.Suppress
(Overflow_Check
);
9030 Scope_Suppress
.Overflow_Mode_General
:= Strict
;
9031 Scope_Suppress
.Overflow_Mode_Assertions
:= Strict
;
9034 Scope_Suppress
.Suppress
(Overflow_Check
) := True;
9037 Analyze_And_Resolve
(N
, Typ
);
9039 Scope_Suppress
.Suppress
(Overflow_Check
) := Svo
;
9040 Scope_Suppress
.Overflow_Mode_General
:= Svg
;
9041 Scope_Suppress
.Overflow_Mode_Assertions
:= Sva
;
9048 procedure Reexpand
(Suppress
: Boolean := False) is
9049 Svg
: constant Overflow_Mode_Type
:=
9050 Scope_Suppress
.Overflow_Mode_General
;
9051 Sva
: constant Overflow_Mode_Type
:=
9052 Scope_Suppress
.Overflow_Mode_Assertions
;
9053 Svo
: constant Boolean :=
9054 Scope_Suppress
.Suppress
(Overflow_Check
);
9057 Scope_Suppress
.Overflow_Mode_General
:= Strict
;
9058 Scope_Suppress
.Overflow_Mode_Assertions
:= Strict
;
9059 Set_Analyzed
(N
, False);
9062 Scope_Suppress
.Suppress
(Overflow_Check
) := True;
9067 Scope_Suppress
.Suppress
(Overflow_Check
) := Svo
;
9068 Scope_Suppress
.Overflow_Mode_General
:= Svg
;
9069 Scope_Suppress
.Overflow_Mode_Assertions
:= Sva
;
9072 -- Start of processing for Minimize_Eliminate_Overflows
9075 -- Default initialize Lo and Hi since these are not guaranteed to be
9081 -- Case where we do not have a signed integer arithmetic operation
9083 if not Is_Signed_Integer_Arithmetic_Op
(N
) then
9085 -- Use the normal Determine_Range routine to get the range. We
9086 -- don't require operands to be valid, invalid values may result in
9087 -- rubbish results where the result has not been properly checked for
9088 -- overflow, that's fine.
9090 Determine_Range
(N
, OK
, Lo
, Hi
, Assume_Valid
=> False);
9092 -- If Determine_Range did not work (can this in fact happen? Not
9093 -- clear but might as well protect), use type bounds.
9096 Lo
:= Intval
(Type_Low_Bound
(Base_Type
(Etype
(N
))));
9097 Hi
:= Intval
(Type_High_Bound
(Base_Type
(Etype
(N
))));
9100 -- If we don't have a binary operator, all we have to do is to set
9101 -- the Hi/Lo range, so we are done.
9105 -- Processing for if expression
9107 elsif Nkind
(N
) = N_If_Expression
then
9109 Then_DE
: constant Node_Id
:= Next
(First
(Expressions
(N
)));
9110 Else_DE
: constant Node_Id
:= Next
(Then_DE
);
9113 Bignum_Operands
:= False;
9115 Minimize_Eliminate_Overflows
9116 (Then_DE
, Lo
, Hi
, Top_Level
=> False);
9119 Bignum_Operands
:= True;
9122 Minimize_Eliminate_Overflows
9123 (Else_DE
, Rlo
, Rhi
, Top_Level
=> False);
9126 Bignum_Operands
:= True;
9128 Long_Long_Integer_Operands
:=
9129 Etype
(Then_DE
) = LLIB
or else Etype
(Else_DE
) = LLIB
;
9135 -- If at least one of our operands is now Bignum, we must rebuild
9136 -- the if expression to use Bignum operands. We will analyze the
9137 -- rebuilt if expression with overflow checks off, since once we
9138 -- are in bignum mode, we are all done with overflow checks.
9140 if Bignum_Operands
then
9142 Make_If_Expression
(Loc
,
9143 Expressions
=> New_List
(
9144 Remove_Head
(Expressions
(N
)),
9145 Convert_To_Bignum
(Then_DE
),
9146 Convert_To_Bignum
(Else_DE
)),
9147 Is_Elsif
=> Is_Elsif
(N
)));
9149 Reanalyze
(RTE
(RE_Bignum
), Suppress
=> True);
9151 -- If we have no Long_Long_Integer operands, then we are in result
9152 -- range, since it means that none of our operands felt the need
9153 -- to worry about overflow (otherwise it would have already been
9154 -- converted to long long integer or bignum). We reexpand to
9155 -- complete the expansion of the if expression (but we do not
9156 -- need to reanalyze).
9158 elsif not Long_Long_Integer_Operands
then
9159 Set_Do_Overflow_Check
(N
, False);
9162 -- Otherwise convert us to long long integer mode. Note that we
9163 -- don't need any further overflow checking at this level.
9166 Convert_To_And_Rewrite
(LLIB
, Then_DE
);
9167 Convert_To_And_Rewrite
(LLIB
, Else_DE
);
9168 Set_Etype
(N
, LLIB
);
9170 -- Now reanalyze with overflow checks off
9172 Set_Do_Overflow_Check
(N
, False);
9173 Reanalyze
(LLIB
, Suppress
=> True);
9179 -- Here for case expression
9181 elsif Nkind
(N
) = N_Case_Expression
then
9182 Bignum_Operands
:= False;
9183 Long_Long_Integer_Operands
:= False;
9189 -- Loop through expressions applying recursive call
9191 Alt
:= First
(Alternatives
(N
));
9192 while Present
(Alt
) loop
9194 Aexp
: constant Node_Id
:= Expression
(Alt
);
9197 Minimize_Eliminate_Overflows
9198 (Aexp
, Lo
, Hi
, Top_Level
=> False);
9201 Bignum_Operands
:= True;
9202 elsif Etype
(Aexp
) = LLIB
then
9203 Long_Long_Integer_Operands
:= True;
9210 -- If we have no bignum or long long integer operands, it means
9211 -- that none of our dependent expressions could raise overflow.
9212 -- In this case, we simply return with no changes except for
9213 -- resetting the overflow flag, since we are done with overflow
9214 -- checks for this node. We will reexpand to get the needed
9215 -- expansion for the case expression, but we do not need to
9216 -- reanalyze, since nothing has changed.
9218 if not (Bignum_Operands
or Long_Long_Integer_Operands
) then
9219 Set_Do_Overflow_Check
(N
, False);
9220 Reexpand
(Suppress
=> True);
9222 -- Otherwise we are going to rebuild the case expression using
9223 -- either bignum or long long integer operands throughout.
9227 Rtype
: Entity_Id
:= Empty
;
9232 New_Alts
:= New_List
;
9233 Alt
:= First
(Alternatives
(N
));
9234 while Present
(Alt
) loop
9235 if Bignum_Operands
then
9236 New_Exp
:= Convert_To_Bignum
(Expression
(Alt
));
9237 Rtype
:= RTE
(RE_Bignum
);
9239 New_Exp
:= Convert_To
(LLIB
, Expression
(Alt
));
9243 Append_To
(New_Alts
,
9244 Make_Case_Expression_Alternative
(Sloc
(Alt
),
9245 Discrete_Choices
=> Discrete_Choices
(Alt
),
9246 Expression
=> New_Exp
));
9252 Make_Case_Expression
(Loc
,
9253 Expression
=> Expression
(N
),
9254 Alternatives
=> New_Alts
));
9256 pragma Assert
(Present
(Rtype
));
9257 Reanalyze
(Rtype
, Suppress
=> True);
9265 -- If we have an arithmetic operator we make recursive calls on the
9266 -- operands to get the ranges (and to properly process the subtree
9267 -- that lies below us).
9269 Minimize_Eliminate_Overflows
9270 (Right_Opnd
(N
), Rlo
, Rhi
, Top_Level
=> False);
9273 Minimize_Eliminate_Overflows
9274 (Left_Opnd
(N
), Llo
, Lhi
, Top_Level
=> False);
9277 -- Record if we have Long_Long_Integer operands
9279 Long_Long_Integer_Operands
:=
9280 Etype
(Right_Opnd
(N
)) = LLIB
9281 or else (Binary
and then Etype
(Left_Opnd
(N
)) = LLIB
);
9283 -- If either operand is a bignum, then result will be a bignum and we
9284 -- don't need to do any range analysis. As previously discussed we could
9285 -- do range analysis in such cases, but it could mean working with giant
9286 -- numbers at compile time for very little gain (the number of cases
9287 -- in which we could slip back from bignum mode is small).
9289 if No
(Rlo
) or else (Binary
and then No
(Llo
)) then
9292 Bignum_Operands
:= True;
9294 -- Otherwise compute result range
9297 Compute_Range_For_Arithmetic_Op
9298 (Nkind
(N
), Llo
, Lhi
, Rlo
, Rhi
, OK
, Lo
, Hi
);
9299 Bignum_Operands
:= False;
9302 -- Here for the case where we have not rewritten anything (no bignum
9303 -- operands or long long integer operands), and we know the result.
9304 -- If we know we are in the result range, and we do not have Bignum
9305 -- operands or Long_Long_Integer operands, we can just reexpand with
9306 -- overflow checks turned off (since we know we cannot have overflow).
9307 -- As always the reexpansion is required to complete expansion of the
9308 -- operator, but we do not need to reanalyze, and we prevent recursion
9309 -- by suppressing the check.
9311 if not (Bignum_Operands
or Long_Long_Integer_Operands
)
9312 and then In_Result_Range
9314 Set_Do_Overflow_Check
(N
, False);
9315 Reexpand
(Suppress
=> True);
9318 -- Here we know that we are not in the result range, and in the general
9319 -- case we will move into either the Bignum or Long_Long_Integer domain
9320 -- to compute the result. However, there is one exception. If we are
9321 -- at the top level, and we do not have Bignum or Long_Long_Integer
9322 -- operands, we will have to immediately convert the result back to
9323 -- the result type, so there is no point in Bignum/Long_Long_Integer
9327 and then not (Bignum_Operands
or Long_Long_Integer_Operands
)
9329 -- One further refinement. If we are at the top level, but our parent
9330 -- is a type conversion, then go into bignum or long long integer node
9331 -- since the result will be converted to that type directly without
9332 -- going through the result type, and we may avoid an overflow. This
9333 -- is the case for example of Long_Long_Integer (A ** 4), where A is
9334 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
9335 -- but does not fit in Integer.
9337 and then Nkind
(Parent
(N
)) /= N_Type_Conversion
9339 -- Here keep original types, but we need to complete analysis
9341 -- One subtlety. We can't just go ahead and do an analyze operation
9342 -- here because it will cause recursion into the whole MINIMIZED/
9343 -- ELIMINATED overflow processing which is not what we want. Here
9344 -- we are at the top level, and we need a check against the result
9345 -- mode (i.e. we want to use STRICT mode). So do exactly that.
9346 -- Also, we have not modified the node, so this is a case where
9347 -- we need to reexpand, but not reanalyze.
9352 -- Cases where we do the operation in Bignum mode. This happens either
9353 -- because one of our operands is in Bignum mode already, or because
9354 -- the computed bounds are outside the bounds of Long_Long_Integer,
9355 -- which in some cases can be indicated by Hi and Lo being No_Uint.
9357 -- Note: we could do better here and in some cases switch back from
9358 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
9359 -- 0 .. 1, but the cases are rare and it is not worth the effort.
9360 -- Failing to do this switching back is only an efficiency issue.
9362 elsif No
(Lo
) or else Lo
< LLLo
or else Hi
> LLHi
then
9364 -- OK, we are definitely outside the range of Long_Long_Integer. The
9365 -- question is whether to move to Bignum mode, or stay in the domain
9366 -- of Long_Long_Integer, signalling that an overflow check is needed.
9368 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
9369 -- the Bignum business. In ELIMINATED mode, we will normally move
9370 -- into Bignum mode, but there is an exception if neither of our
9371 -- operands is Bignum now, and we are at the top level (Top_Level
9372 -- set True). In this case, there is no point in moving into Bignum
9373 -- mode to prevent overflow if the caller will immediately convert
9374 -- the Bignum value back to LLI with an overflow check. It's more
9375 -- efficient to stay in LLI mode with an overflow check (if needed)
9377 if Check_Mode
= Minimized
9378 or else (Top_Level
and not Bignum_Operands
)
9380 if Do_Overflow_Check
(N
) then
9381 Enable_Overflow_Check
(N
);
9384 -- The result now has to be in Long_Long_Integer mode, so adjust
9385 -- the possible range to reflect this. Note these calls also
9386 -- change No_Uint values from the top level case to LLI bounds.
9391 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
9394 pragma Assert
(Check_Mode
= Eliminated
);
9403 Fent
:= RTE
(RE_Big_Abs
);
9406 Fent
:= RTE
(RE_Big_Add
);
9409 Fent
:= RTE
(RE_Big_Div
);
9412 Fent
:= RTE
(RE_Big_Exp
);
9415 Fent
:= RTE
(RE_Big_Neg
);
9418 Fent
:= RTE
(RE_Big_Mod
);
9420 when N_Op_Multiply
=>
9421 Fent
:= RTE
(RE_Big_Mul
);
9424 Fent
:= RTE
(RE_Big_Rem
);
9426 when N_Op_Subtract
=>
9427 Fent
:= RTE
(RE_Big_Sub
);
9429 -- Anything else is an internal error, this includes the
9430 -- N_Op_Plus case, since how can plus cause the result
9431 -- to be out of range if the operand is in range?
9434 raise Program_Error
;
9437 -- Construct argument list for Bignum call, converting our
9438 -- operands to Bignum form if they are not already there.
9443 Append_To
(Args
, Convert_To_Bignum
(Left_Opnd
(N
)));
9446 Append_To
(Args
, Convert_To_Bignum
(Right_Opnd
(N
)));
9448 -- Now rewrite the arithmetic operator with a call to the
9449 -- corresponding bignum function.
9452 Make_Function_Call
(Loc
,
9453 Name
=> New_Occurrence_Of
(Fent
, Loc
),
9454 Parameter_Associations
=> Args
));
9455 Reanalyze
(RTE
(RE_Bignum
), Suppress
=> True);
9457 -- Indicate result is Bignum mode
9465 -- Otherwise we are in range of Long_Long_Integer, so no overflow
9466 -- check is required, at least not yet.
9469 Set_Do_Overflow_Check
(N
, False);
9472 -- Here we are not in Bignum territory, but we may have long long
9473 -- integer operands that need special handling. First a special check:
9474 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9475 -- it means we converted it to prevent overflow, but exponentiation
9476 -- requires a Natural right operand, so convert it back to Natural.
9477 -- This conversion may raise an exception which is fine.
9479 if Nkind
(N
) = N_Op_Expon
and then Etype
(Right_Opnd
(N
)) = LLIB
then
9480 Convert_To_And_Rewrite
(Standard_Natural
, Right_Opnd
(N
));
9483 -- Here we will do the operation in Long_Long_Integer. We do this even
9484 -- if we know an overflow check is required, better to do this in long
9485 -- long integer mode, since we are less likely to overflow.
9487 -- Convert right or only operand to Long_Long_Integer, except that
9488 -- we do not touch the exponentiation right operand.
9490 if Nkind
(N
) /= N_Op_Expon
then
9491 Convert_To_And_Rewrite
(LLIB
, Right_Opnd
(N
));
9494 -- Convert left operand to Long_Long_Integer for binary case
9497 Convert_To_And_Rewrite
(LLIB
, Left_Opnd
(N
));
9500 -- Reset node to unanalyzed
9502 Set_Analyzed
(N
, False);
9503 Set_Etype
(N
, Empty
);
9504 Set_Entity
(N
, Empty
);
9506 -- Now analyze this new node. This reanalysis will complete processing
9507 -- for the node. In particular we will complete the expansion of an
9508 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9509 -- we will complete any division checks (since we have not changed the
9510 -- setting of the Do_Division_Check flag).
9512 -- We do this reanalysis in STRICT mode to avoid recursion into the
9513 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
9516 SG
: constant Overflow_Mode_Type
:=
9517 Scope_Suppress
.Overflow_Mode_General
;
9518 SA
: constant Overflow_Mode_Type
:=
9519 Scope_Suppress
.Overflow_Mode_Assertions
;
9522 Scope_Suppress
.Overflow_Mode_General
:= Strict
;
9523 Scope_Suppress
.Overflow_Mode_Assertions
:= Strict
;
9525 if not Do_Overflow_Check
(N
) then
9526 Reanalyze
(LLIB
, Suppress
=> True);
9531 Scope_Suppress
.Overflow_Mode_General
:= SG
;
9532 Scope_Suppress
.Overflow_Mode_Assertions
:= SA
;
9534 end Minimize_Eliminate_Overflows
;
9536 -------------------------
9537 -- Overflow_Check_Mode --
9538 -------------------------
9540 function Overflow_Check_Mode
return Overflow_Mode_Type
is
9542 if In_Assertion_Expr
= 0 then
9543 return Scope_Suppress
.Overflow_Mode_General
;
9545 return Scope_Suppress
.Overflow_Mode_Assertions
;
9547 end Overflow_Check_Mode
;
9549 --------------------------------
9550 -- Overflow_Checks_Suppressed --
9551 --------------------------------
9553 function Overflow_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
9555 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
9556 return Is_Check_Suppressed
(E
, Overflow_Check
);
9558 return Scope_Suppress
.Suppress
(Overflow_Check
);
9560 end Overflow_Checks_Suppressed
;
9562 ---------------------------------
9563 -- Predicate_Checks_Suppressed --
9564 ---------------------------------
9566 function Predicate_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
9568 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
9569 return Is_Check_Suppressed
(E
, Predicate_Check
);
9571 return Scope_Suppress
.Suppress
(Predicate_Check
);
9573 end Predicate_Checks_Suppressed
;
9575 -----------------------------
9576 -- Range_Checks_Suppressed --
9577 -----------------------------
9579 function Range_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
9582 if Kill_Range_Checks
(E
) then
9585 elsif Checks_May_Be_Suppressed
(E
) then
9586 return Is_Check_Suppressed
(E
, Range_Check
);
9590 return Scope_Suppress
.Suppress
(Range_Check
);
9591 end Range_Checks_Suppressed
;
9593 -----------------------------------------
9594 -- Range_Or_Validity_Checks_Suppressed --
9595 -----------------------------------------
9597 -- Note: the coding would be simpler here if we simply made appropriate
9598 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9599 -- duplicated checks which we prefer to avoid.
9601 function Range_Or_Validity_Checks_Suppressed
9602 (Expr
: Node_Id
) return Boolean
9605 -- Immediate return if scope checks suppressed for either check
9607 if Scope_Suppress
.Suppress
(Range_Check
)
9609 Scope_Suppress
.Suppress
(Validity_Check
)
9614 -- If no expression, that's odd, decide that checks are suppressed,
9615 -- since we don't want anyone trying to do checks in this case, which
9616 -- is most likely the result of some other error.
9622 -- Expression is present, so perform suppress checks on type
9625 Typ
: constant Entity_Id
:= Etype
(Expr
);
9627 if Checks_May_Be_Suppressed
(Typ
)
9628 and then (Is_Check_Suppressed
(Typ
, Range_Check
)
9630 Is_Check_Suppressed
(Typ
, Validity_Check
))
9636 -- If expression is an entity name, perform checks on this entity
9638 if Is_Entity_Name
(Expr
) then
9640 Ent
: constant Entity_Id
:= Entity
(Expr
);
9642 if Checks_May_Be_Suppressed
(Ent
) then
9643 return Is_Check_Suppressed
(Ent
, Range_Check
)
9644 or else Is_Check_Suppressed
(Ent
, Validity_Check
);
9649 -- If we fall through, no checks suppressed
9652 end Range_Or_Validity_Checks_Suppressed
;
9658 procedure Remove_Checks
(Expr
: Node_Id
) is
9659 function Process
(N
: Node_Id
) return Traverse_Result
;
9660 -- Process a single node during the traversal
9662 procedure Traverse
is new Traverse_Proc
(Process
);
9663 -- The traversal procedure itself
9669 function Process
(N
: Node_Id
) return Traverse_Result
is
9671 if Nkind
(N
) not in N_Subexpr
then
9675 Set_Do_Range_Check
(N
, False);
9679 Traverse
(Left_Opnd
(N
));
9682 when N_Attribute_Reference
=>
9683 Set_Do_Overflow_Check
(N
, False);
9686 Set_Do_Overflow_Check
(N
, False);
9690 Set_Do_Division_Check
(N
, False);
9693 Set_Do_Length_Check
(N
, False);
9696 Set_Do_Division_Check
(N
, False);
9699 Set_Do_Length_Check
(N
, False);
9702 Set_Do_Division_Check
(N
, False);
9705 Set_Do_Length_Check
(N
, False);
9712 Traverse
(Left_Opnd
(N
));
9715 when N_Selected_Component
=>
9716 Set_Do_Discriminant_Check
(N
, False);
9718 when N_Type_Conversion
=>
9719 Set_Do_Length_Check
(N
, False);
9720 Set_Do_Overflow_Check
(N
, False);
9729 -- Start of processing for Remove_Checks
9735 ----------------------------
9736 -- Selected_Length_Checks --
9737 ----------------------------
9739 function Selected_Length_Checks
9741 Target_Typ
: Entity_Id
;
9742 Source_Typ
: Entity_Id
;
9743 Warn_Node
: Node_Id
) return Check_Result
9745 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
9748 Expr_Actual
: Node_Id
;
9750 Cond
: Node_Id
:= Empty
;
9751 Do_Access
: Boolean := False;
9752 Wnode
: Node_Id
:= Warn_Node
;
9753 Ret_Result
: Check_Result
:= (Empty
, Empty
);
9754 Num_Checks
: Natural := 0;
9756 procedure Add_Check
(N
: Node_Id
);
9757 -- Adds the action given to Ret_Result if N is non-Empty
9759 function Get_E_Length
(E
: Entity_Id
; Indx
: Nat
) return Node_Id
;
9760 -- Return E'Length (Indx)
9762 function Get_N_Length
(N
: Node_Id
; Indx
: Nat
) return Node_Id
;
9763 -- Return N'Length (Indx)
9765 function Same_Bounds
(L
: Node_Id
; R
: Node_Id
) return Boolean;
9766 -- True for equal literals and for nodes that denote the same constant
9767 -- entity, even if its value is not a static constant. This includes the
9768 -- case of a discriminal reference within an init proc. Removes some
9769 -- obviously superfluous checks.
9771 function Length_E_Cond
9772 (Exptyp
: Entity_Id
;
9774 Indx
: Nat
) return Node_Id
;
9775 -- Returns expression to compute:
9776 -- Typ'Length /= Exptyp'Length
9778 function Length_N_Cond
9781 Indx
: Nat
) return Node_Id
;
9782 -- Returns expression to compute:
9783 -- Typ'Length /= Exp'Length
9785 function Length_Mismatch_Info_Message
9786 (Left_Element_Count
: Unat
;
9787 Right_Element_Count
: Unat
) return String;
9788 -- Returns a message indicating how many elements were expected
9789 -- (Left_Element_Count) and how many were found (Right_Element_Count).
9795 procedure Add_Check
(N
: Node_Id
) is
9799 -- We do not support inserting more than 2 checks on the same
9800 -- node. If this happens it means we have already added an
9801 -- unconditional raise, so we can skip the other checks safely
9802 -- since N will always raise an exception.
9804 if Num_Checks
= 2 then
9808 pragma Assert
(Num_Checks
<= 1);
9809 Num_Checks
:= Num_Checks
+ 1;
9810 Ret_Result
(Num_Checks
) := N
;
9818 function Get_E_Length
(E
: Entity_Id
; Indx
: Nat
) return Node_Id
is
9819 SE
: constant Entity_Id
:= Scope
(E
);
9821 E1
: Entity_Id
:= E
;
9824 if Ekind
(Scope
(E
)) = E_Record_Type
9825 and then Has_Discriminants
(Scope
(E
))
9827 N
:= Build_Discriminal_Subtype_Of_Component
(E
);
9830 Insert_Action
(Expr
, N
);
9831 E1
:= Defining_Identifier
(N
);
9835 if Ekind
(E1
) = E_String_Literal_Subtype
then
9837 Make_Integer_Literal
(Loc
,
9838 Intval
=> String_Literal_Length
(E1
));
9840 elsif SE
/= Standard_Standard
9841 and then Ekind
(Scope
(SE
)) = E_Protected_Type
9842 and then Has_Discriminants
(Scope
(SE
))
9843 and then Has_Completion
(Scope
(SE
))
9844 and then not Inside_Init_Proc
9846 -- If the type whose length is needed is a private component
9847 -- constrained by a discriminant, we must expand the 'Length
9848 -- attribute into an explicit computation, using the discriminal
9849 -- of the current protected operation. This is because the actual
9850 -- type of the prival is constructed after the protected opera-
9851 -- tion has been fully expanded.
9854 Indx_Type
: Node_Id
;
9855 Bounds
: Range_Nodes
;
9856 Do_Expand
: Boolean := False;
9859 Indx_Type
:= First_Index
(E
);
9861 for J
in 1 .. Indx
- 1 loop
9862 Next_Index
(Indx_Type
);
9865 Bounds
:= Get_Index_Bounds
(Indx_Type
);
9867 if Nkind
(Bounds
.First
) = N_Identifier
9868 and then Ekind
(Entity
(Bounds
.First
)) = E_In_Parameter
9870 Bounds
.First
:= Get_Discriminal
(E
, Bounds
.First
);
9874 if Nkind
(Bounds
.Last
) = N_Identifier
9875 and then Ekind
(Entity
(Bounds
.Last
)) = E_In_Parameter
9877 Bounds
.Last
:= Get_Discriminal
(E
, Bounds
.Last
);
9882 if not Is_Entity_Name
(Bounds
.First
) then
9884 Duplicate_Subexpr_No_Checks
(Bounds
.First
);
9887 if not Is_Entity_Name
(Bounds
.Last
) then
9888 Bounds
.First
:= Duplicate_Subexpr_No_Checks
(Bounds
.Last
);
9894 Make_Op_Subtract
(Loc
,
9895 Left_Opnd
=> Bounds
.Last
,
9896 Right_Opnd
=> Bounds
.First
),
9898 Right_Opnd
=> Make_Integer_Literal
(Loc
, 1));
9903 Make_Attribute_Reference
(Loc
,
9904 Attribute_Name
=> Name_Length
,
9906 New_Occurrence_Of
(E1
, Loc
));
9909 Set_Expressions
(N
, New_List
(
9910 Make_Integer_Literal
(Loc
, Indx
)));
9919 Make_Attribute_Reference
(Loc
,
9920 Attribute_Name
=> Name_Length
,
9922 New_Occurrence_Of
(E1
, Loc
));
9925 Set_Expressions
(N
, New_List
(
9926 Make_Integer_Literal
(Loc
, Indx
)));
9937 function Get_N_Length
(N
: Node_Id
; Indx
: Nat
) return Node_Id
is
9940 Make_Attribute_Reference
(Loc
,
9941 Attribute_Name
=> Name_Length
,
9943 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
9944 Expressions
=> New_List
(
9945 Make_Integer_Literal
(Loc
, Indx
)));
9952 function Length_E_Cond
9953 (Exptyp
: Entity_Id
;
9955 Indx
: Nat
) return Node_Id
9960 Left_Opnd
=> Get_E_Length
(Typ
, Indx
),
9961 Right_Opnd
=> Get_E_Length
(Exptyp
, Indx
));
9968 function Length_N_Cond
9971 Indx
: Nat
) return Node_Id
9976 Left_Opnd
=> Get_E_Length
(Typ
, Indx
),
9977 Right_Opnd
=> Get_N_Length
(Exp
, Indx
));
9980 ----------------------------------
9981 -- Length_Mismatch_Info_Message --
9982 ----------------------------------
9984 function Length_Mismatch_Info_Message
9985 (Left_Element_Count
: Unat
;
9986 Right_Element_Count
: Unat
) return String
9989 function Plural_Vs_Singular_Ending
(Count
: Unat
) return String;
9990 -- Returns an empty string if Count is 1; otherwise returns "s"
9992 function Plural_Vs_Singular_Ending
(Count
: Unat
) return String is
9999 end Plural_Vs_Singular_Ending
;
10003 & UI_Image
(Left_Element_Count
, Format
=> Decimal
)
10005 & Plural_Vs_Singular_Ending
(Left_Element_Count
)
10007 & UI_Image
(Right_Element_Count
, Format
=> Decimal
)
10009 & Plural_Vs_Singular_Ending
(Right_Element_Count
);
10010 -- "Format => Decimal" above is needed because otherwise UI_Image
10011 -- can sometimes return a hexadecimal number 16#...#, but "#" means
10012 -- something special to Errout. A previous version used the default
10013 -- Auto, which was essentially the same bug as documented here:
10014 -- https://xkcd.com/327/ .
10015 end Length_Mismatch_Info_Message
;
10021 function Same_Bounds
(L
: Node_Id
; R
: Node_Id
) return Boolean is
10024 (Nkind
(L
) = N_Integer_Literal
10025 and then Nkind
(R
) = N_Integer_Literal
10026 and then Intval
(L
) = Intval
(R
))
10029 (Is_Entity_Name
(L
)
10030 and then Ekind
(Entity
(L
)) = E_Constant
10031 and then ((Is_Entity_Name
(R
)
10032 and then Entity
(L
) = Entity
(R
))
10034 (Nkind
(R
) = N_Type_Conversion
10035 and then Is_Entity_Name
(Expression
(R
))
10036 and then Entity
(L
) = Entity
(Expression
(R
)))))
10039 (Is_Entity_Name
(R
)
10040 and then Ekind
(Entity
(R
)) = E_Constant
10041 and then Nkind
(L
) = N_Type_Conversion
10042 and then Is_Entity_Name
(Expression
(L
))
10043 and then Entity
(R
) = Entity
(Expression
(L
)))
10046 (Is_Entity_Name
(L
)
10047 and then Is_Entity_Name
(R
)
10048 and then Entity
(L
) = Entity
(R
)
10049 and then Ekind
(Entity
(L
)) = E_In_Parameter
10050 and then Inside_Init_Proc
);
10053 -- Start of processing for Selected_Length_Checks
10056 -- Checks will be applied only when generating code
10058 if not Expander_Active
then
10062 if Target_Typ
= Any_Type
10063 or else Target_Typ
= Any_Composite
10064 or else Raises_Constraint_Error
(Expr
)
10073 T_Typ
:= Target_Typ
;
10075 if No
(Source_Typ
) then
10076 S_Typ
:= Etype
(Expr
);
10078 S_Typ
:= Source_Typ
;
10081 if S_Typ
= Any_Type
or else S_Typ
= Any_Composite
then
10085 if Is_Access_Type
(T_Typ
) and then Is_Access_Type
(S_Typ
) then
10086 S_Typ
:= Designated_Type
(S_Typ
);
10087 T_Typ
:= Designated_Type
(T_Typ
);
10090 -- A simple optimization for the null case
10092 if Known_Null
(Expr
) then
10097 if Is_Array_Type
(T_Typ
) and then Is_Array_Type
(S_Typ
) then
10098 if Is_Constrained
(T_Typ
) then
10100 -- The checking code to be generated will freeze the corresponding
10101 -- array type. However, we must freeze the type now, so that the
10102 -- freeze node does not appear within the generated if expression,
10103 -- but ahead of it.
10105 Freeze_Before
(Expr
, T_Typ
);
10107 Expr_Actual
:= Get_Referenced_Object
(Expr
);
10108 Exptyp
:= Get_Actual_Subtype
(Expr
);
10110 if Is_Access_Type
(Exptyp
) then
10111 Exptyp
:= Designated_Type
(Exptyp
);
10114 -- String_Literal case. This needs to be handled specially be-
10115 -- cause no index types are available for string literals. The
10116 -- condition is simply:
10118 -- T_Typ'Length = string-literal-length
10120 if Nkind
(Expr_Actual
) = N_String_Literal
10121 and then Ekind
(Etype
(Expr_Actual
)) = E_String_Literal_Subtype
10125 Left_Opnd
=> Get_E_Length
(T_Typ
, 1),
10127 Make_Integer_Literal
(Loc
,
10129 String_Literal_Length
(Etype
(Expr_Actual
))));
10131 -- General array case. Here we have a usable actual subtype for
10132 -- the expression, and the condition is built from the two types
10135 -- T_Typ'Length /= Exptyp'Length or else
10136 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
10137 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
10140 elsif Is_Constrained
(Exptyp
) then
10142 Ndims
: constant Nat
:= Number_Dimensions
(T_Typ
);
10146 L_Bounds
: Range_Nodes
;
10147 R_Bounds
: Range_Nodes
;
10150 Ref_Node
: Node_Id
;
10153 -- At the library level, we need to ensure that the type of
10154 -- the object is elaborated before the check itself is
10155 -- emitted. This is only done if the object is in the
10156 -- current compilation unit, otherwise the type is frozen
10157 -- and elaborated in its unit.
10159 if Is_Itype
(Exptyp
)
10161 Ekind
(Cunit_Entity
(Current_Sem_Unit
)) = E_Package
10163 not In_Package_Body
(Cunit_Entity
(Current_Sem_Unit
))
10164 and then In_Open_Scopes
(Scope
(Exptyp
))
10166 Ref_Node
:= Make_Itype_Reference
(Sloc
(Expr
));
10167 Set_Itype
(Ref_Node
, Exptyp
);
10168 Insert_Action
(Expr
, Ref_Node
);
10171 L_Index
:= First_Index
(T_Typ
);
10172 R_Index
:= First_Index
(Exptyp
);
10174 for Indx
in 1 .. Ndims
loop
10175 if not (Nkind
(L_Index
) = N_Raise_Constraint_Error
10177 Nkind
(R_Index
) = N_Raise_Constraint_Error
)
10179 L_Bounds
:= Get_Index_Bounds
(L_Index
);
10180 R_Bounds
:= Get_Index_Bounds
(R_Index
);
10182 -- Deal with compile time length check. Note that we
10183 -- skip this in the access case, because the access
10184 -- value may be null, so we cannot know statically.
10187 and then Compile_Time_Known_Value
(L_Bounds
.First
)
10188 and then Compile_Time_Known_Value
(L_Bounds
.Last
)
10189 and then Compile_Time_Known_Value
(R_Bounds
.First
)
10190 and then Compile_Time_Known_Value
(R_Bounds
.Last
)
10192 if Expr_Value
(L_Bounds
.Last
) >=
10193 Expr_Value
(L_Bounds
.First
)
10195 L_Length
:= Expr_Value
(L_Bounds
.Last
) -
10196 Expr_Value
(L_Bounds
.First
) + 1;
10198 L_Length
:= UI_From_Int
(0);
10201 if Expr_Value
(R_Bounds
.Last
) >=
10202 Expr_Value
(R_Bounds
.First
)
10204 R_Length
:= Expr_Value
(R_Bounds
.Last
) -
10205 Expr_Value
(R_Bounds
.First
) + 1;
10207 R_Length
:= UI_From_Int
(0);
10210 if L_Length
> R_Length
then
10212 (Compile_Time_Constraint_Error
10213 (Wnode
, "too few elements for}!!??", T_Typ
,
10214 Extra_Msg
=> Length_Mismatch_Info_Message
10215 (L_Length
, R_Length
)));
10217 elsif L_Length
< R_Length
then
10219 (Compile_Time_Constraint_Error
10220 (Wnode
, "too many elements for}!!??", T_Typ
,
10221 Extra_Msg
=> Length_Mismatch_Info_Message
10222 (L_Length
, R_Length
)));
10225 -- The comparison for an individual index subtype
10226 -- is omitted if the corresponding index subtypes
10227 -- statically match, since the result is known to
10228 -- be true. Note that this test is worth while even
10229 -- though we do static evaluation, because non-static
10230 -- subtypes can statically match.
10233 Subtypes_Statically_Match
10234 (Etype
(L_Index
), Etype
(R_Index
))
10237 (Same_Bounds
(L_Bounds
.First
, R_Bounds
.First
)
10239 Same_Bounds
(L_Bounds
.Last
, R_Bounds
.Last
))
10242 (Cond
, Length_E_Cond
(Exptyp
, T_Typ
, Indx
));
10251 -- Handle cases where we do not get a usable actual subtype that
10252 -- is constrained. This happens for example in the function call
10253 -- and explicit dereference cases. In these cases, we have to get
10254 -- the length or range from the expression itself, making sure we
10255 -- do not evaluate it more than once.
10257 -- Here Expr is the original expression, or more properly the
10258 -- result of applying Duplicate_Expr to the original tree, forcing
10259 -- the result to be a name.
10263 Ndims
: constant Pos
:= Number_Dimensions
(T_Typ
);
10266 -- Build the condition for the explicit dereference case
10268 for Indx
in 1 .. Ndims
loop
10270 (Cond
, Length_N_Cond
(Expr
, T_Typ
, Indx
));
10277 -- Construct the test and insert into the tree
10279 if Present
(Cond
) then
10281 Cond
:= Guard_Access
(Cond
, Loc
, Expr
);
10285 (Make_Raise_Constraint_Error
(Loc
,
10287 Reason
=> CE_Length_Check_Failed
));
10291 end Selected_Length_Checks
;
10293 ---------------------------
10294 -- Selected_Range_Checks --
10295 ---------------------------
10297 function Selected_Range_Checks
10299 Target_Typ
: Entity_Id
;
10300 Source_Typ
: Entity_Id
;
10301 Warn_Node
: Node_Id
) return Check_Result
10303 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
10306 Expr_Actual
: Node_Id
;
10307 Exptyp
: Entity_Id
;
10308 Cond
: Node_Id
:= Empty
;
10309 Do_Access
: Boolean := False;
10310 Wnode
: Node_Id
:= Warn_Node
;
10311 Ret_Result
: Check_Result
:= (Empty
, Empty
);
10312 Num_Checks
: Natural := 0;
10314 procedure Add_Check
(N
: Node_Id
);
10315 -- Adds the action given to Ret_Result if N is non-Empty
10317 function Discrete_Range_Cond
10319 Typ
: Entity_Id
) return Node_Id
;
10320 -- Returns expression to compute:
10321 -- Low_Bound (Exp) < Typ'First
10323 -- High_Bound (Exp) > Typ'Last
10325 function Discrete_Expr_Cond
10327 Typ
: Entity_Id
) return Node_Id
;
10328 -- Returns expression to compute:
10333 function Get_E_First_Or_Last
10337 Nam
: Name_Id
) return Node_Id
;
10338 -- Returns an attribute reference
10339 -- E'First or E'Last
10340 -- with a source location of Loc.
10342 -- Nam is Name_First or Name_Last, according to which attribute is
10343 -- desired. If Indx is non-zero, it is passed as a literal in the
10344 -- Expressions of the attribute reference (identifying the desired
10345 -- array dimension).
10347 function Get_N_First
(N
: Node_Id
; Indx
: Nat
) return Node_Id
;
10348 function Get_N_Last
(N
: Node_Id
; Indx
: Nat
) return Node_Id
;
10349 -- Returns expression to compute:
10350 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
10352 function Is_Cond_Expr_Ge
(N
: Node_Id
; V
: Node_Id
) return Boolean;
10353 function Is_Cond_Expr_Le
(N
: Node_Id
; V
: Node_Id
) return Boolean;
10354 -- Return True if N is a conditional expression whose dependent
10355 -- expressions are all known and greater/lower than or equal to V.
10357 function Range_E_Cond
10358 (Exptyp
: Entity_Id
;
10362 -- Returns expression to compute:
10363 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
10365 function Range_Equal_E_Cond
10366 (Exptyp
: Entity_Id
;
10368 Indx
: Nat
) return Node_Id
;
10369 -- Returns expression to compute:
10370 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
10372 function Range_N_Cond
10375 Indx
: Nat
) return Node_Id
;
10376 -- Return expression to compute:
10377 -- Exp'First < Typ'First or else Exp'Last > Typ'Last
10379 function "<" (Left
, Right
: Node_Id
) return Boolean
10380 is (if Is_Floating_Point_Type
(S_Typ
)
10381 then Expr_Value_R
(Left
) < Expr_Value_R
(Right
)
10382 else Expr_Value
(Left
) < Expr_Value
(Right
));
10383 function "<=" (Left
, Right
: Node_Id
) return Boolean
10384 is (if Is_Floating_Point_Type
(S_Typ
)
10385 then Expr_Value_R
(Left
) <= Expr_Value_R
(Right
)
10386 else Expr_Value
(Left
) <= Expr_Value
(Right
));
10387 -- Convenience comparison functions of integer or floating point values
10393 procedure Add_Check
(N
: Node_Id
) is
10395 if Present
(N
) then
10397 -- We do not support inserting more than 2 checks on the same
10398 -- node. If this happens it means we have already added an
10399 -- unconditional raise, so we can skip the other checks safely
10400 -- since N will always raise an exception.
10402 if Num_Checks
= 2 then
10406 pragma Assert
(Num_Checks
<= 1);
10407 Num_Checks
:= Num_Checks
+ 1;
10408 Ret_Result
(Num_Checks
) := N
;
10412 -------------------------
10413 -- Discrete_Expr_Cond --
10414 -------------------------
10416 function Discrete_Expr_Cond
10418 Typ
: Entity_Id
) return Node_Id
10426 Convert_To
(Base_Type
(Typ
),
10427 Duplicate_Subexpr_No_Checks
(Exp
)),
10429 Convert_To
(Base_Type
(Typ
),
10430 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_First
))),
10435 Convert_To
(Base_Type
(Typ
),
10436 Duplicate_Subexpr_No_Checks
(Exp
)),
10440 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_Last
))));
10441 end Discrete_Expr_Cond
;
10443 -------------------------
10444 -- Discrete_Range_Cond --
10445 -------------------------
10447 function Discrete_Range_Cond
10449 Typ
: Entity_Id
) return Node_Id
10451 LB
: Node_Id
:= Low_Bound
(Exp
);
10452 HB
: Node_Id
:= High_Bound
(Exp
);
10454 Left_Opnd
: Node_Id
;
10455 Right_Opnd
: Node_Id
;
10458 if Nkind
(LB
) = N_Identifier
10459 and then Ekind
(Entity
(LB
)) = E_Discriminant
10461 LB
:= New_Occurrence_Of
(Discriminal
(Entity
(LB
)), Loc
);
10464 -- If the index type has a fixed lower bound, then we require an
10465 -- exact match of the range's lower bound against that fixed lower
10468 if Is_Fixed_Lower_Bound_Index_Subtype
(Typ
) then
10473 (Base_Type
(Typ
), Duplicate_Subexpr_No_Checks
(LB
)),
10478 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_First
)));
10480 -- Otherwise we do the expected less-than comparison
10487 (Base_Type
(Typ
), Duplicate_Subexpr_No_Checks
(LB
)),
10492 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_First
)));
10495 if Nkind
(HB
) = N_Identifier
10496 and then Ekind
(Entity
(HB
)) = E_Discriminant
10498 HB
:= New_Occurrence_Of
(Discriminal
(Entity
(HB
)), Loc
);
10505 (Base_Type
(Typ
), Duplicate_Subexpr_No_Checks
(HB
)),
10510 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_Last
)));
10512 return Make_Or_Else
(Loc
, Left_Opnd
, Right_Opnd
);
10513 end Discrete_Range_Cond
;
10515 -------------------------
10516 -- Get_E_First_Or_Last --
10517 -------------------------
10519 function Get_E_First_Or_Last
10523 Nam
: Name_Id
) return Node_Id
10528 Exprs
:= New_List
(Make_Integer_Literal
(Loc
, UI_From_Int
(Indx
)));
10533 return Make_Attribute_Reference
(Loc
,
10534 Prefix
=> New_Occurrence_Of
(E
, Loc
),
10535 Attribute_Name
=> Nam
,
10536 Expressions
=> Exprs
);
10537 end Get_E_First_Or_Last
;
10543 function Get_N_First
(N
: Node_Id
; Indx
: Nat
) return Node_Id
is
10546 Make_Attribute_Reference
(Loc
,
10547 Attribute_Name
=> Name_First
,
10549 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
10550 Expressions
=> New_List
(
10551 Make_Integer_Literal
(Loc
, Indx
)));
10558 function Get_N_Last
(N
: Node_Id
; Indx
: Nat
) return Node_Id
is
10561 Make_Attribute_Reference
(Loc
,
10562 Attribute_Name
=> Name_Last
,
10564 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
10565 Expressions
=> New_List
(
10566 Make_Integer_Literal
(Loc
, Indx
)));
10569 ---------------------
10570 -- Is_Cond_Expr_Ge --
10571 ---------------------
10573 function Is_Cond_Expr_Ge
(N
: Node_Id
; V
: Node_Id
) return Boolean is
10575 -- Only if expressions are relevant for the time being
10577 if Nkind
(N
) = N_If_Expression
then
10579 Cond
: constant Node_Id
:= First
(Expressions
(N
));
10580 Thenx
: constant Node_Id
:= Next
(Cond
);
10581 Elsex
: constant Node_Id
:= Next
(Thenx
);
10584 return Compile_Time_Known_Value
(Thenx
)
10585 and then V
<= Thenx
10587 ((Compile_Time_Known_Value
(Elsex
) and then V
<= Elsex
)
10588 or else Is_Cond_Expr_Ge
(Elsex
, V
));
10594 end Is_Cond_Expr_Ge
;
10596 ---------------------
10597 -- Is_Cond_Expr_Le --
10598 ---------------------
10600 function Is_Cond_Expr_Le
(N
: Node_Id
; V
: Node_Id
) return Boolean is
10602 -- Only if expressions are relevant for the time being
10604 if Nkind
(N
) = N_If_Expression
then
10606 Cond
: constant Node_Id
:= First
(Expressions
(N
));
10607 Thenx
: constant Node_Id
:= Next
(Cond
);
10608 Elsex
: constant Node_Id
:= Next
(Thenx
);
10611 return Compile_Time_Known_Value
(Thenx
)
10612 and then Thenx
<= V
10614 ((Compile_Time_Known_Value
(Elsex
) and then Elsex
<= V
)
10615 or else Is_Cond_Expr_Le
(Elsex
, V
));
10621 end Is_Cond_Expr_Le
;
10627 function Range_E_Cond
10628 (Exptyp
: Entity_Id
;
10630 Indx
: Nat
) return Node_Id
10638 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_First
),
10640 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_First
)),
10645 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_Last
),
10647 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_Last
)));
10650 ------------------------
10651 -- Range_Equal_E_Cond --
10652 ------------------------
10654 function Range_Equal_E_Cond
10655 (Exptyp
: Entity_Id
;
10657 Indx
: Nat
) return Node_Id
10665 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_First
),
10667 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_First
)),
10672 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_Last
),
10674 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_Last
)));
10675 end Range_Equal_E_Cond
;
10681 function Range_N_Cond
10684 Indx
: Nat
) return Node_Id
10692 Get_N_First
(Exp
, Indx
),
10694 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_First
)),
10699 Get_N_Last
(Exp
, Indx
),
10701 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_Last
)));
10704 -- Start of processing for Selected_Range_Checks
10707 -- Checks will be applied only when generating code. In GNATprove mode,
10708 -- we do not apply the checks, but we still call Selected_Range_Checks
10709 -- outside of generics to possibly issue errors on SPARK code when a
10710 -- run-time error can be detected at compile time.
10712 if Inside_A_Generic
or (not GNATprove_Mode
and not Expander_Active
) then
10716 if Target_Typ
= Any_Type
10717 or else Target_Typ
= Any_Composite
10718 or else Raises_Constraint_Error
(Expr
)
10727 T_Typ
:= Target_Typ
;
10729 if No
(Source_Typ
) then
10730 S_Typ
:= Etype
(Expr
);
10732 S_Typ
:= Source_Typ
;
10735 if S_Typ
= Any_Type
or else S_Typ
= Any_Composite
then
10739 -- The order of evaluating T_Typ before S_Typ seems to be critical
10740 -- because S_Typ can be derived from Etype (Expr), if it's not passed
10741 -- in, and since Node can be an N_Range node, it might be invalid.
10742 -- Should there be an assert check somewhere for taking the Etype of
10743 -- an N_Range node ???
10745 if Is_Access_Type
(T_Typ
) and then Is_Access_Type
(S_Typ
) then
10746 S_Typ
:= Designated_Type
(S_Typ
);
10747 T_Typ
:= Designated_Type
(T_Typ
);
10750 -- A simple optimization for the null case
10752 if Known_Null
(Expr
) then
10757 -- For an N_Range Node, check for a null range and then if not
10758 -- null generate a range check action.
10760 if Nkind
(Expr
) = N_Range
then
10762 -- There's no point in checking a range against itself
10764 if Expr
= Scalar_Range
(T_Typ
) then
10769 T_LB
: constant Node_Id
:= Type_Low_Bound
(T_Typ
);
10770 T_HB
: constant Node_Id
:= Type_High_Bound
(T_Typ
);
10771 Known_T_LB
: constant Boolean := Compile_Time_Known_Value
(T_LB
);
10772 Known_T_HB
: constant Boolean := Compile_Time_Known_Value
(T_HB
);
10774 LB
: Node_Id
:= Low_Bound
(Expr
);
10775 HB
: Node_Id
:= High_Bound
(Expr
);
10776 Known_LB
: Boolean := False;
10777 Known_HB
: Boolean := False;
10778 Check_Added
: Boolean := False;
10780 Out_Of_Range_L
: Boolean := False;
10781 Out_Of_Range_H
: Boolean := False;
10784 -- Compute what is known at compile time
10786 if Known_T_LB
and Known_T_HB
then
10787 if Compile_Time_Known_Value
(LB
) then
10790 -- There's no point in checking that a bound is within its
10791 -- own range so pretend that it is known in this case. First
10792 -- deal with low bound.
10794 elsif Ekind
(Etype
(LB
)) = E_Signed_Integer_Subtype
10795 and then Scalar_Range
(Etype
(LB
)) = Scalar_Range
(T_Typ
)
10800 -- Similarly; deal with the case where the low bound is a
10801 -- conditional expression whose result is greater than or
10802 -- equal to the target low bound.
10804 elsif Is_Cond_Expr_Ge
(LB
, T_LB
) then
10809 -- Likewise for the high bound
10811 if Compile_Time_Known_Value
(HB
) then
10814 elsif Ekind
(Etype
(HB
)) = E_Signed_Integer_Subtype
10815 and then Scalar_Range
(Etype
(HB
)) = Scalar_Range
(T_Typ
)
10820 elsif Is_Cond_Expr_Le
(HB
, T_HB
) then
10826 -- Check for the simple cases where we can do the check at
10827 -- compile time. This is skipped if we have an access type, since
10828 -- the access value may be null.
10830 if not Do_Access
and then Not_Null_Range
(LB
, HB
) then
10833 Out_Of_Range_L
:= LB
< T_LB
;
10836 if Known_T_HB
and not Out_Of_Range_L
then
10837 Out_Of_Range_L
:= T_HB
< LB
;
10840 if Out_Of_Range_L
then
10841 if No
(Warn_Node
) then
10843 (Compile_Time_Constraint_Error
10845 "static value out of range of}??", T_Typ
));
10846 Check_Added
:= True;
10850 (Compile_Time_Constraint_Error
10852 "static range out of bounds of}??", T_Typ
));
10853 Check_Added
:= True;
10858 -- Flag the case of a fixed-lower-bound index where the static
10859 -- bounds are not equal.
10862 and then Is_Fixed_Lower_Bound_Index_Subtype
(T_Typ
)
10864 and then Known_T_LB
10865 and then Expr_Value
(LB
) /= Expr_Value
(T_LB
)
10868 (Compile_Time_Constraint_Error
10869 ((if Present
(Warn_Node
)
10870 then Warn_Node
else Low_Bound
(Expr
)),
10871 "static value does not equal lower bound of}??",
10873 Check_Added
:= True;
10878 Out_Of_Range_H
:= T_HB
< HB
;
10881 if Known_T_LB
and not Out_Of_Range_H
then
10882 Out_Of_Range_H
:= HB
< T_LB
;
10885 if Out_Of_Range_H
then
10886 if No
(Warn_Node
) then
10888 (Compile_Time_Constraint_Error
10889 (High_Bound
(Expr
),
10890 "static value out of range of}??", T_Typ
));
10891 Check_Added
:= True;
10895 (Compile_Time_Constraint_Error
10897 "static range out of bounds of}??", T_Typ
));
10898 Check_Added
:= True;
10904 -- Check for the case where not everything is static
10909 or else not Known_T_LB
10910 or else not Known_LB
10911 or else not Known_T_HB
10912 or else not Known_HB
)
10915 LB
: Node_Id
:= Low_Bound
(Expr
);
10916 HB
: Node_Id
:= High_Bound
(Expr
);
10919 -- If either bound is a discriminant and we are within the
10920 -- record declaration, it is a use of the discriminant in a
10921 -- constraint of a component, and nothing can be checked
10922 -- here. The check will be emitted within the init proc.
10923 -- Before then, the discriminal has no real meaning.
10924 -- Similarly, if the entity is a discriminal, there is no
10925 -- check to perform yet.
10927 -- The same holds within a discriminated synchronized type,
10928 -- where the discriminant may constrain a component or an
10931 if Nkind
(LB
) = N_Identifier
10932 and then Denotes_Discriminant
(LB
, True)
10934 if Current_Scope
= Scope
(Entity
(LB
))
10935 or else Is_Concurrent_Type
(Current_Scope
)
10936 or else Ekind
(Entity
(LB
)) /= E_Discriminant
10941 New_Occurrence_Of
(Discriminal
(Entity
(LB
)), Loc
);
10945 if Nkind
(HB
) = N_Identifier
10946 and then Denotes_Discriminant
(HB
, True)
10948 if Current_Scope
= Scope
(Entity
(HB
))
10949 or else Is_Concurrent_Type
(Current_Scope
)
10950 or else Ekind
(Entity
(HB
)) /= E_Discriminant
10955 New_Occurrence_Of
(Discriminal
(Entity
(HB
)), Loc
);
10959 Cond
:= Discrete_Range_Cond
(Expr
, T_Typ
);
10960 Set_Paren_Count
(Cond
, 1);
10963 Make_And_Then
(Loc
,
10967 Convert_To
(Base_Type
(Etype
(HB
)),
10968 Duplicate_Subexpr_No_Checks
(HB
)),
10970 Convert_To
(Base_Type
(Etype
(LB
)),
10971 Duplicate_Subexpr_No_Checks
(LB
))),
10972 Right_Opnd
=> Cond
);
10977 elsif Is_Scalar_Type
(S_Typ
) then
10979 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10980 -- except the above simply sets a flag in the node and lets the
10981 -- check be generated based on the Etype of the expression.
10982 -- Sometimes, however we want to do a dynamic check against an
10983 -- arbitrary target type, so we do that here.
10985 if Ekind
(Base_Type
(S_Typ
)) /= Ekind
(Base_Type
(T_Typ
)) then
10986 Cond
:= Discrete_Expr_Cond
(Expr
, T_Typ
);
10988 -- For literals, we can tell if the constraint error will be
10989 -- raised at compile time, so we never need a dynamic check, but
10990 -- if the exception will be raised, then post the usual warning,
10991 -- and replace the literal with a raise constraint error
10992 -- expression. As usual, skip this for access types
10994 elsif Compile_Time_Known_Value
(Expr
) and then not Do_Access
then
10995 if Is_Out_Of_Range
(Expr
, T_Typ
) then
10997 -- Bounds of the type are static and the literal is out of
10998 -- range so output a warning message.
11000 if No
(Warn_Node
) then
11002 (Compile_Time_Constraint_Error
11003 (Expr
, "static value out of range of}??", T_Typ
));
11007 (Compile_Time_Constraint_Error
11008 (Wnode
, "static value out of range of}??", T_Typ
));
11011 Cond
:= Discrete_Expr_Cond
(Expr
, T_Typ
);
11014 -- Here for the case of a non-static expression, we need a runtime
11015 -- check unless the source type range is guaranteed to be in the
11016 -- range of the target type.
11019 if not In_Subrange_Of
(S_Typ
, T_Typ
) then
11020 Cond
:= Discrete_Expr_Cond
(Expr
, T_Typ
);
11025 if Is_Array_Type
(T_Typ
) and then Is_Array_Type
(S_Typ
) then
11026 if Is_Constrained
(T_Typ
) then
11027 Expr_Actual
:= Get_Referenced_Object
(Expr
);
11028 Exptyp
:= Get_Actual_Subtype
(Expr_Actual
);
11030 if Is_Access_Type
(Exptyp
) then
11031 Exptyp
:= Designated_Type
(Exptyp
);
11034 -- String_Literal case. This needs to be handled specially be-
11035 -- cause no index types are available for string literals. The
11036 -- condition is simply:
11038 -- T_Typ'Length = string-literal-length
11040 if Nkind
(Expr_Actual
) = N_String_Literal
then
11043 -- General array case. Here we have a usable actual subtype for
11044 -- the expression, and the condition is built from the two types
11046 -- T_Typ'First < Exptyp'First or else
11047 -- T_Typ'Last > Exptyp'Last or else
11048 -- T_Typ'First(1) < Exptyp'First(1) or else
11049 -- T_Typ'Last(1) > Exptyp'Last(1) or else
11052 elsif Is_Constrained
(Exptyp
) then
11054 Ndims
: constant Pos
:= Number_Dimensions
(T_Typ
);
11060 L_Index
:= First_Index
(T_Typ
);
11061 R_Index
:= First_Index
(Exptyp
);
11063 for Indx
in 1 .. Ndims
loop
11064 if not (Nkind
(L_Index
) = N_Raise_Constraint_Error
11066 Nkind
(R_Index
) = N_Raise_Constraint_Error
)
11068 -- Deal with compile time length check. Note that we
11069 -- skip this in the access case, because the access
11070 -- value may be null, so we cannot know statically.
11073 Subtypes_Statically_Match
11074 (Etype
(L_Index
), Etype
(R_Index
))
11076 -- If the target type is constrained then we
11077 -- have to check for exact equality of bounds
11078 -- (required for qualified expressions).
11080 if Is_Constrained
(T_Typ
) then
11083 Range_Equal_E_Cond
(Exptyp
, T_Typ
, Indx
));
11086 (Cond
, Range_E_Cond
(Exptyp
, T_Typ
, Indx
));
11096 -- Handle cases where we do not get a usable actual subtype that
11097 -- is constrained. This happens for example in the function call
11098 -- and explicit dereference cases. In these cases, we have to get
11099 -- the length or range from the expression itself, making sure we
11100 -- do not evaluate it more than once.
11102 -- Here Expr is the original expression, or more properly the
11103 -- result of applying Duplicate_Expr to the original tree,
11104 -- forcing the result to be a name.
11108 Ndims
: constant Pos
:= Number_Dimensions
(T_Typ
);
11111 -- Build the condition for the explicit dereference case
11113 for Indx
in 1 .. Ndims
loop
11115 (Cond
, Range_N_Cond
(Expr
, T_Typ
, Indx
));
11120 -- If the context is a qualified_expression where the subtype is
11121 -- an unconstrained array subtype with fixed-lower-bound indexes,
11122 -- then consistency checks must be done between the lower bounds
11123 -- of any such indexes and the corresponding lower bounds of the
11124 -- qualified array object.
11126 elsif Is_Fixed_Lower_Bound_Array_Subtype
(T_Typ
)
11127 and then Nkind
(Parent
(Expr
)) = N_Qualified_Expression
11128 and then not Do_Access
11131 Ndims
: constant Pos
:= Number_Dimensions
(T_Typ
);
11133 Qual_Index
: Node_Id
;
11134 Expr_Index
: Node_Id
;
11137 Expr_Actual
:= Get_Referenced_Object
(Expr
);
11138 Exptyp
:= Get_Actual_Subtype
(Expr_Actual
);
11140 Qual_Index
:= First_Index
(T_Typ
);
11141 Expr_Index
:= First_Index
(Exptyp
);
11143 for Indx
in 1 .. Ndims
loop
11144 if Nkind
(Expr_Index
) /= N_Raise_Constraint_Error
then
11146 -- If this index of the qualifying array subtype has
11147 -- a fixed lower bound, then apply a check that the
11148 -- corresponding lower bound of the array expression
11151 if Is_Fixed_Lower_Bound_Index_Subtype
(Etype
(Qual_Index
))
11157 Get_E_First_Or_Last
11158 (Loc
, Exptyp
, Indx
, Name_First
),
11161 (Type_Low_Bound
(Etype
(Qual_Index
)))));
11171 -- For a conversion to an unconstrained array type, generate an
11172 -- Action to check that the bounds of the source value are within
11173 -- the constraints imposed by the target type (RM 4.6(38)). No
11174 -- check is needed for a conversion to an access to unconstrained
11175 -- array type, as 4.6(24.15/2) requires the designated subtypes
11176 -- of the two access types to statically match.
11178 if Nkind
(Parent
(Expr
)) = N_Type_Conversion
11179 and then not Do_Access
11182 Opnd_Index
: Node_Id
;
11183 Targ_Index
: Node_Id
;
11184 Opnd_Range
: Node_Id
;
11187 Opnd_Index
:= First_Index
(Get_Actual_Subtype
(Expr
));
11188 Targ_Index
:= First_Index
(T_Typ
);
11189 while Present
(Opnd_Index
) loop
11191 -- If the index is a range, use its bounds. If it is an
11192 -- entity (as will be the case if it is a named subtype
11193 -- or an itype created for a slice) retrieve its range.
11195 if Is_Entity_Name
(Opnd_Index
)
11196 and then Is_Type
(Entity
(Opnd_Index
))
11198 Opnd_Range
:= Scalar_Range
(Entity
(Opnd_Index
));
11200 Opnd_Range
:= Opnd_Index
;
11203 if Nkind
(Opnd_Range
) = N_Range
then
11205 (Low_Bound
(Opnd_Range
), Etype
(Targ_Index
),
11206 Assume_Valid
=> True)
11209 (High_Bound
(Opnd_Range
), Etype
(Targ_Index
),
11210 Assume_Valid
=> True)
11214 -- If null range, no check needed
11217 Compile_Time_Known_Value
(High_Bound
(Opnd_Range
))
11219 Compile_Time_Known_Value
(Low_Bound
(Opnd_Range
))
11221 Expr_Value
(High_Bound
(Opnd_Range
)) <
11222 Expr_Value
(Low_Bound
(Opnd_Range
))
11226 elsif Is_Out_Of_Range
11227 (Low_Bound
(Opnd_Range
), Etype
(Targ_Index
),
11228 Assume_Valid
=> True)
11231 (High_Bound
(Opnd_Range
), Etype
(Targ_Index
),
11232 Assume_Valid
=> True)
11235 (Compile_Time_Constraint_Error
11236 (Wnode
, "value out of range of}??", T_Typ
));
11241 Discrete_Range_Cond
11242 (Opnd_Range
, Etype
(Targ_Index
)));
11246 Next_Index
(Opnd_Index
);
11247 Next_Index
(Targ_Index
);
11254 -- Construct the test and insert into the tree
11256 if Present
(Cond
) then
11258 Cond
:= Guard_Access
(Cond
, Loc
, Expr
);
11262 (Make_Raise_Constraint_Error
(Loc
,
11264 Reason
=> CE_Range_Check_Failed
));
11268 end Selected_Range_Checks
;
11270 -------------------------------
11271 -- Storage_Checks_Suppressed --
11272 -------------------------------
11274 function Storage_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
11276 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
11277 return Is_Check_Suppressed
(E
, Storage_Check
);
11279 return Scope_Suppress
.Suppress
(Storage_Check
);
11281 end Storage_Checks_Suppressed
;
11283 ---------------------------
11284 -- Tag_Checks_Suppressed --
11285 ---------------------------
11287 function Tag_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
11290 and then Checks_May_Be_Suppressed
(E
)
11292 return Is_Check_Suppressed
(E
, Tag_Check
);
11294 return Scope_Suppress
.Suppress
(Tag_Check
);
11296 end Tag_Checks_Suppressed
;
11298 ---------------------------------------
11299 -- Validate_Alignment_Check_Warnings --
11300 ---------------------------------------
11302 procedure Validate_Alignment_Check_Warnings
is
11304 for J
in Alignment_Warnings
.First
.. Alignment_Warnings
.Last
loop
11306 AWR
: Alignment_Warnings_Record
11307 renames Alignment_Warnings
.Table
(J
);
11309 if Known_Alignment
(AWR
.E
)
11310 and then ((Present
(AWR
.A
)
11311 and then AWR
.A
mod Alignment
(AWR
.E
) = 0)
11312 or else (Present
(AWR
.P
)
11313 and then Has_Compatible_Alignment
11314 (AWR
.E
, AWR
.P
, True) =
11317 Delete_Warning_And_Continuations
(AWR
.W
);
11321 end Validate_Alignment_Check_Warnings
;
11323 --------------------------
11324 -- Validity_Check_Range --
11325 --------------------------
11327 procedure Validity_Check_Range
11329 Related_Id
: Entity_Id
:= Empty
) is
11331 if Validity_Checks_On
and Validity_Check_Operands
then
11332 if Nkind
(N
) = N_Range
then
11334 (Expr
=> Low_Bound
(N
),
11335 Related_Id
=> Related_Id
,
11336 Is_Low_Bound
=> True);
11339 (Expr
=> High_Bound
(N
),
11340 Related_Id
=> Related_Id
,
11341 Is_High_Bound
=> True);
11344 end Validity_Check_Range
;