1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2007, 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 Errout; use Errout;
30 with Exp_Ch2; use Exp_Ch2;
31 with Exp_Ch11; use Exp_Ch11;
32 with Exp_Pakd; use Exp_Pakd;
33 with Exp_Util; use Exp_Util;
34 with Elists; use Elists;
35 with Eval_Fat; use Eval_Fat;
36 with Freeze; use Freeze;
38 with Nlists; use Nlists;
39 with Nmake; use Nmake;
41 with Output; use Output;
42 with Restrict; use Restrict;
43 with Rident; use Rident;
44 with Rtsfind; use Rtsfind;
46 with Sem_Eval; use Sem_Eval;
47 with Sem_Ch3; use Sem_Ch3;
48 with Sem_Ch8; use Sem_Ch8;
49 with Sem_Res; use Sem_Res;
50 with Sem_Util; use Sem_Util;
51 with Sem_Warn; use Sem_Warn;
52 with Sinfo; use Sinfo;
53 with Sinput; use Sinput;
54 with Snames; use Snames;
55 with Sprint; use Sprint;
56 with Stand; use Stand;
57 with Targparm; use Targparm;
58 with Tbuild; use Tbuild;
59 with Ttypes; use Ttypes;
60 with Urealp; use Urealp;
61 with Validsw; use Validsw;
63 package body Checks is
65 -- General note: many of these routines are concerned with generating
66 -- checking code to make sure that constraint error is raised at runtime.
67 -- Clearly this code is only needed if the expander is active, since
68 -- otherwise we will not be generating code or going into the runtime
71 -- We therefore disconnect most of these checks if the expander is
72 -- inactive. This has the additional benefit that we do not need to
73 -- worry about the tree being messed up by previous errors (since errors
74 -- turn off expansion anyway).
76 -- There are a few exceptions to the above rule. For instance routines
77 -- such as Apply_Scalar_Range_Check that do not insert any code can be
78 -- safely called even when the Expander is inactive (but Errors_Detected
79 -- is 0). The benefit of executing this code when expansion is off, is
80 -- the ability to emit constraint error warning for static expressions
81 -- even when we are not generating code.
83 -------------------------------------
84 -- Suppression of Redundant Checks --
85 -------------------------------------
87 -- This unit implements a limited circuit for removal of redundant
88 -- checks. The processing is based on a tracing of simple sequential
89 -- flow. For any sequence of statements, we save expressions that are
90 -- marked to be checked, and then if the same expression appears later
91 -- with the same check, then under certain circumstances, the second
92 -- check can be suppressed.
94 -- Basically, we can suppress the check if we know for certain that
95 -- the previous expression has been elaborated (together with its
96 -- check), and we know that the exception frame is the same, and that
97 -- nothing has happened to change the result of the exception.
99 -- Let us examine each of these three conditions in turn to describe
100 -- how we ensure that this condition is met.
102 -- First, we need to know for certain that the previous expression has
103 -- been executed. This is done principly by the mechanism of calling
104 -- Conditional_Statements_Begin at the start of any statement sequence
105 -- and Conditional_Statements_End at the end. The End call causes all
106 -- checks remembered since the Begin call to be discarded. This does
107 -- miss a few cases, notably the case of a nested BEGIN-END block with
108 -- no exception handlers. But the important thing is to be conservative.
109 -- The other protection is that all checks are discarded if a label
110 -- is encountered, since then the assumption of sequential execution
111 -- is violated, and we don't know enough about the flow.
113 -- Second, we need to know that the exception frame is the same. We
114 -- do this by killing all remembered checks when we enter a new frame.
115 -- Again, that's over-conservative, but generally the cases we can help
116 -- with are pretty local anyway (like the body of a loop for example).
118 -- Third, we must be sure to forget any checks which are no longer valid.
119 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
120 -- used to note any changes to local variables. We only attempt to deal
121 -- with checks involving local variables, so we do not need to worry
122 -- about global variables. Second, a call to any non-global procedure
123 -- causes us to abandon all stored checks, since such a all may affect
124 -- the values of any local variables.
126 -- The following define the data structures used to deal with remembering
127 -- checks so that redundant checks can be eliminated as described above.
129 -- Right now, the only expressions that we deal with are of the form of
130 -- simple local objects (either declared locally, or IN parameters) or
131 -- such objects plus/minus a compile time known constant. We can do
132 -- more later on if it seems worthwhile, but this catches many simple
133 -- cases in practice.
135 -- The following record type reflects a single saved check. An entry
136 -- is made in the stack of saved checks if and only if the expression
137 -- has been elaborated with the indicated checks.
139 type Saved_Check is record
141 -- Set True if entry is killed by Kill_Checks
144 -- The entity involved in the expression that is checked
147 -- A compile time value indicating the result of adding or
148 -- subtracting a compile time value. This value is to be
149 -- added to the value of the Entity. A value of zero is
150 -- used for the case of a simple entity reference.
152 Check_Type : Character;
153 -- This is set to 'R' for a range check (in which case Target_Type
154 -- is set to the target type for the range check) or to 'O' for an
155 -- overflow check (in which case Target_Type is set to Empty).
157 Target_Type : Entity_Id;
158 -- Used only if Do_Range_Check is set. Records the target type for
159 -- the check. We need this, because a check is a duplicate only if
160 -- it has a the same target type (or more accurately one with a
161 -- range that is smaller or equal to the stored target type of a
165 -- The following table keeps track of saved checks. Rather than use an
166 -- extensible table. We just use a table of fixed size, and we discard
167 -- any saved checks that do not fit. That's very unlikely to happen and
168 -- this is only an optimization in any case.
170 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
171 -- Array of saved checks
173 Num_Saved_Checks : Nat := 0;
174 -- Number of saved checks
176 -- The following stack keeps track of statement ranges. It is treated
177 -- as a stack. When Conditional_Statements_Begin is called, an entry
178 -- is pushed onto this stack containing the value of Num_Saved_Checks
179 -- at the time of the call. Then when Conditional_Statements_End is
180 -- called, this value is popped off and used to reset Num_Saved_Checks.
182 -- Note: again, this is a fixed length stack with a size that should
183 -- always be fine. If the value of the stack pointer goes above the
184 -- limit, then we just forget all saved checks.
186 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
187 Saved_Checks_TOS : Nat := 0;
189 -----------------------
190 -- Local Subprograms --
191 -----------------------
193 procedure Apply_Float_Conversion_Check
195 Target_Typ : Entity_Id);
196 -- The checks on a conversion from a floating-point type to an integer
197 -- type are delicate. They have to be performed before conversion, they
198 -- have to raise an exception when the operand is a NaN, and rounding must
199 -- be taken into account to determine the safe bounds of the operand.
201 procedure Apply_Selected_Length_Checks
203 Target_Typ : Entity_Id;
204 Source_Typ : Entity_Id;
205 Do_Static : Boolean);
206 -- This is the subprogram that does all the work for Apply_Length_Check
207 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
208 -- described for the above routines. The Do_Static flag indicates that
209 -- only a static check is to be done.
211 procedure Apply_Selected_Range_Checks
213 Target_Typ : Entity_Id;
214 Source_Typ : Entity_Id;
215 Do_Static : Boolean);
216 -- This is the subprogram that does all the work for Apply_Range_Check.
217 -- Expr, Target_Typ and Source_Typ are as described for the above
218 -- routine. The Do_Static flag indicates that only a static check is
221 type Check_Type is new Check_Id range Access_Check .. Division_Check;
222 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
223 -- This function is used to see if an access or division by zero check is
224 -- needed. The check is to be applied to a single variable appearing in the
225 -- source, and N is the node for the reference. If N is not of this form,
226 -- True is returned with no further processing. If N is of the right form,
227 -- then further processing determines if the given Check is needed.
229 -- The particular circuit is to see if we have the case of a check that is
230 -- not needed because it appears in the right operand of a short circuited
231 -- conditional where the left operand guards the check. For example:
233 -- if Var = 0 or else Q / Var > 12 then
237 -- In this example, the division check is not required. At the same time
238 -- we can issue warnings for suspicious use of non-short-circuited forms,
241 -- if Var = 0 or Q / Var > 12 then
247 Check_Type : Character;
248 Target_Type : Entity_Id;
249 Entry_OK : out Boolean;
253 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
254 -- to see if a check is of the form for optimization, and if so, to see
255 -- if it has already been performed. Expr is the expression to check,
256 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
257 -- Target_Type is the target type for a range check, and Empty for an
258 -- overflow check. If the entry is not of the form for optimization,
259 -- then Entry_OK is set to False, and the remaining out parameters
260 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
261 -- entity and offset from the expression. Check_Num is the number of
262 -- a matching saved entry in Saved_Checks, or zero if no such entry
265 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
266 -- If a discriminal is used in constraining a prival, Return reference
267 -- to the discriminal of the protected body (which renames the parameter
268 -- of the enclosing protected operation). This clumsy transformation is
269 -- needed because privals are created too late and their actual subtypes
270 -- are not available when analysing the bodies of the protected operations.
271 -- This function is called whenever the bound is an entity and the scope
272 -- indicates a protected operation. If the bound is an in-parameter of
273 -- a protected operation that is not a prival, the function returns the
275 -- To be cleaned up???
277 function Guard_Access
280 Ck_Node : Node_Id) return Node_Id;
281 -- In the access type case, guard the test with a test to ensure
282 -- that the access value is non-null, since the checks do not
283 -- not apply to null access values.
285 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
286 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
287 -- Constraint_Error node.
289 function Range_Or_Validity_Checks_Suppressed
290 (Expr : Node_Id) return Boolean;
291 -- Returns True if either range or validity checks or both are suppressed
292 -- for the type of the given expression, or, if the expression is the name
293 -- of an entity, if these checks are suppressed for the entity.
295 function Selected_Length_Checks
297 Target_Typ : Entity_Id;
298 Source_Typ : Entity_Id;
299 Warn_Node : Node_Id) return Check_Result;
300 -- Like Apply_Selected_Length_Checks, except it doesn't modify
301 -- anything, just returns a list of nodes as described in the spec of
302 -- this package for the Range_Check function.
304 function Selected_Range_Checks
306 Target_Typ : Entity_Id;
307 Source_Typ : Entity_Id;
308 Warn_Node : Node_Id) return Check_Result;
309 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
310 -- just returns a list of nodes as described in the spec of this package
311 -- for the Range_Check function.
313 ------------------------------
314 -- Access_Checks_Suppressed --
315 ------------------------------
317 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
319 if Present (E) and then Checks_May_Be_Suppressed (E) then
320 return Is_Check_Suppressed (E, Access_Check);
322 return Scope_Suppress (Access_Check);
324 end Access_Checks_Suppressed;
326 -------------------------------------
327 -- Accessibility_Checks_Suppressed --
328 -------------------------------------
330 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
332 if Present (E) and then Checks_May_Be_Suppressed (E) then
333 return Is_Check_Suppressed (E, Accessibility_Check);
335 return Scope_Suppress (Accessibility_Check);
337 end Accessibility_Checks_Suppressed;
339 -----------------------------
340 -- Activate_Division_Check --
341 -----------------------------
343 procedure Activate_Division_Check (N : Node_Id) is
345 Set_Do_Division_Check (N, True);
346 Possible_Local_Raise (N, Standard_Constraint_Error);
347 end Activate_Division_Check;
349 -----------------------------
350 -- Activate_Overflow_Check --
351 -----------------------------
353 procedure Activate_Overflow_Check (N : Node_Id) is
355 Set_Do_Overflow_Check (N, True);
356 Possible_Local_Raise (N, Standard_Constraint_Error);
357 end Activate_Overflow_Check;
359 --------------------------
360 -- Activate_Range_Check --
361 --------------------------
363 procedure Activate_Range_Check (N : Node_Id) is
365 Set_Do_Range_Check (N, True);
366 Possible_Local_Raise (N, Standard_Constraint_Error);
367 end Activate_Range_Check;
369 ---------------------------------
370 -- Alignment_Checks_Suppressed --
371 ---------------------------------
373 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
375 if Present (E) and then Checks_May_Be_Suppressed (E) then
376 return Is_Check_Suppressed (E, Alignment_Check);
378 return Scope_Suppress (Alignment_Check);
380 end Alignment_Checks_Suppressed;
382 -------------------------
383 -- Append_Range_Checks --
384 -------------------------
386 procedure Append_Range_Checks
387 (Checks : Check_Result;
389 Suppress_Typ : Entity_Id;
390 Static_Sloc : Source_Ptr;
393 Internal_Flag_Node : constant Node_Id := Flag_Node;
394 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
396 Checks_On : constant Boolean :=
397 (not Index_Checks_Suppressed (Suppress_Typ))
399 (not Range_Checks_Suppressed (Suppress_Typ));
402 -- For now we just return if Checks_On is false, however this should
403 -- be enhanced to check for an always True value in the condition
404 -- and to generate a compilation warning???
406 if not Checks_On then
411 exit when No (Checks (J));
413 if Nkind (Checks (J)) = N_Raise_Constraint_Error
414 and then Present (Condition (Checks (J)))
416 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
417 Append_To (Stmts, Checks (J));
418 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
424 Make_Raise_Constraint_Error (Internal_Static_Sloc,
425 Reason => CE_Range_Check_Failed));
428 end Append_Range_Checks;
430 ------------------------
431 -- Apply_Access_Check --
432 ------------------------
434 procedure Apply_Access_Check (N : Node_Id) is
435 P : constant Node_Id := Prefix (N);
438 -- We do not need checks if we are not generating code (i.e. the
439 -- expander is not active). This is not just an optimization, there
440 -- are cases (e.g. with pragma Debug) where generating the checks
441 -- can cause real trouble).
443 if not Expander_Active then
447 -- No check if short circuiting makes check unnecessary
449 if not Check_Needed (P, Access_Check) then
453 -- Otherwise go ahead and install the check
455 Install_Null_Excluding_Check (P);
456 end Apply_Access_Check;
458 -------------------------------
459 -- Apply_Accessibility_Check --
460 -------------------------------
462 procedure Apply_Accessibility_Check (N : Node_Id; Typ : Entity_Id) is
463 Loc : constant Source_Ptr := Sloc (N);
464 Param_Ent : constant Entity_Id := Param_Entity (N);
465 Param_Level : Node_Id;
466 Type_Level : Node_Id;
469 if Inside_A_Generic then
472 -- Only apply the run-time check if the access parameter
473 -- has an associated extra access level parameter and
474 -- when the level of the type is less deep than the level
475 -- of the access parameter.
477 elsif Present (Param_Ent)
478 and then Present (Extra_Accessibility (Param_Ent))
479 and then UI_Gt (Object_Access_Level (N),
480 Type_Access_Level (Typ))
481 and then not Accessibility_Checks_Suppressed (Param_Ent)
482 and then not Accessibility_Checks_Suppressed (Typ)
485 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
488 Make_Integer_Literal (Loc, Type_Access_Level (Typ));
490 -- Raise Program_Error if the accessibility level of the the access
491 -- parameter is deeper than the level of the target access type.
494 Make_Raise_Program_Error (Loc,
497 Left_Opnd => Param_Level,
498 Right_Opnd => Type_Level),
499 Reason => PE_Accessibility_Check_Failed));
501 Analyze_And_Resolve (N);
503 end Apply_Accessibility_Check;
505 --------------------------------
506 -- Apply_Address_Clause_Check --
507 --------------------------------
509 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
510 AC : constant Node_Id := Address_Clause (E);
511 Loc : constant Source_Ptr := Sloc (AC);
512 Typ : constant Entity_Id := Etype (E);
513 Aexp : constant Node_Id := Expression (AC);
516 -- Address expression (not necessarily the same as Aexp, for example
517 -- when Aexp is a reference to a constant, in which case Expr gets
518 -- reset to reference the value expression of the constant.
520 Size_Warning_Output : Boolean := False;
521 -- If we output a size warning we set this True, to stop generating
522 -- what is likely to be an unuseful redundant alignment warning.
524 procedure Compile_Time_Bad_Alignment;
525 -- Post error warnings when alignment is known to be incompatible. Note
526 -- that we do not go as far as inserting a raise of Program_Error since
527 -- this is an erroneous case, and it may happen that we are lucky and an
528 -- underaligned address turns out to be OK after all. Also this warning
529 -- is suppressed if we already complained about the size.
531 --------------------------------
532 -- Compile_Time_Bad_Alignment --
533 --------------------------------
535 procedure Compile_Time_Bad_Alignment is
537 if not Size_Warning_Output
538 and then Address_Clause_Overlay_Warnings
541 ("?specified address for& may be inconsistent with alignment ",
544 ("\?program execution may be erroneous (RM 13.3(27))",
546 Set_Address_Warning_Posted (AC);
548 end Compile_Time_Bad_Alignment;
550 -- Start of processing for Apply_Address_Clause_Check
553 -- First obtain expression from address clause
555 Expr := Expression (AC);
557 -- The following loop digs for the real expression to use in the check
560 -- For constant, get constant expression
562 if Is_Entity_Name (Expr)
563 and then Ekind (Entity (Expr)) = E_Constant
565 Expr := Constant_Value (Entity (Expr));
567 -- For unchecked conversion, get result to convert
569 elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
570 Expr := Expression (Expr);
572 -- For (common case) of To_Address call, get argument
574 elsif Nkind (Expr) = N_Function_Call
575 and then Is_Entity_Name (Name (Expr))
576 and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
578 Expr := First (Parameter_Associations (Expr));
580 if Nkind (Expr) = N_Parameter_Association then
581 Expr := Explicit_Actual_Parameter (Expr);
584 -- We finally have the real expression
591 -- Output a warning if we have the situation of
593 -- for X'Address use Y'Address
595 -- and X and Y both have known object sizes, and Y is smaller than X
597 if Nkind (Expr) = N_Attribute_Reference
598 and then Attribute_Name (Expr) = Name_Address
599 and then Is_Entity_Name (Prefix (Expr))
602 Exp_Ent : constant Entity_Id := Entity (Prefix (Expr));
603 Obj_Size : Uint := No_Uint;
604 Exp_Size : Uint := No_Uint;
607 if Known_Esize (E) then
608 Obj_Size := Esize (E);
609 elsif Known_Esize (Etype (E)) then
610 Obj_Size := Esize (Etype (E));
613 if Known_Esize (Exp_Ent) then
614 Exp_Size := Esize (Exp_Ent);
615 elsif Known_Esize (Etype (Exp_Ent)) then
616 Exp_Size := Esize (Etype (Exp_Ent));
619 if Obj_Size /= No_Uint
620 and then Exp_Size /= No_Uint
621 and then Obj_Size > Exp_Size
622 and then not Warnings_Off (E)
624 if Address_Clause_Overlay_Warnings then
626 ("?& overlays smaller object", Aexp, E);
628 ("\?program execution may be erroneous", Aexp, E);
629 Size_Warning_Output := True;
630 Set_Address_Warning_Posted (AC);
636 -- See if alignment check needed. Note that we never need a check if the
637 -- maximum alignment is one, since the check will always succeed.
639 -- Note: we do not check for checks suppressed here, since that check
640 -- was done in Sem_Ch13 when the address clause was processed. We are
641 -- only called if checks were not suppressed. The reason for this is
642 -- that we have to delay the call to Apply_Alignment_Check till freeze
643 -- time (so that all types etc are elaborated), but we have to check
644 -- the status of check suppressing at the point of the address clause.
647 or else not Check_Address_Alignment (AC)
648 or else Maximum_Alignment = 1
653 -- See if we know that Expr is a bad alignment at compile time
655 if Compile_Time_Known_Value (Expr)
656 and then (Known_Alignment (E) or else Known_Alignment (Typ))
659 AL : Uint := Alignment (Typ);
662 -- The object alignment might be more restrictive than the
665 if Known_Alignment (E) then
669 if Expr_Value (Expr) mod AL /= 0 then
670 Compile_Time_Bad_Alignment;
676 -- If the expression has the form X'Address, then we can find out if
677 -- the object X has an alignment that is compatible with the object E.
679 elsif Nkind (Expr) = N_Attribute_Reference
680 and then Attribute_Name (Expr) = Name_Address
683 AR : constant Alignment_Result :=
684 Has_Compatible_Alignment (E, Prefix (Expr));
686 if AR = Known_Compatible then
688 elsif AR = Known_Incompatible then
689 Compile_Time_Bad_Alignment;
694 -- Here we do not know if the value is acceptable. Stricly we don't have
695 -- to do anything, since if the alignment is bad, we have an erroneous
696 -- program. However we are allowed to check for erroneous conditions and
697 -- we decide to do this by default if the check is not suppressed.
699 -- However, don't do the check if elaboration code is unwanted
701 if Restriction_Active (No_Elaboration_Code) then
704 -- Generate a check to raise PE if alignment may be inappropriate
707 -- If the original expression is a non-static constant, use the
708 -- name of the constant itself rather than duplicating its
709 -- defining expression, which was extracted above.
711 -- Note: Expr is empty if the address-clause is applied to in-mode
712 -- actuals (allowed by 13.1(22)).
714 if not Present (Expr)
716 (Is_Entity_Name (Expression (AC))
717 and then Ekind (Entity (Expression (AC))) = E_Constant
718 and then Nkind (Parent (Entity (Expression (AC))))
719 = N_Object_Declaration)
721 Expr := New_Copy_Tree (Expression (AC));
723 Remove_Side_Effects (Expr);
726 Insert_After_And_Analyze (N,
727 Make_Raise_Program_Error (Loc,
734 (RTE (RE_Integer_Address), Expr),
736 Make_Attribute_Reference (Loc,
737 Prefix => New_Occurrence_Of (E, Loc),
738 Attribute_Name => Name_Alignment)),
739 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
740 Reason => PE_Misaligned_Address_Value),
741 Suppress => All_Checks);
746 -- If we have some missing run time component in configurable run time
747 -- mode then just skip the check (it is not required in any case).
749 when RE_Not_Available =>
751 end Apply_Address_Clause_Check;
753 -------------------------------------
754 -- Apply_Arithmetic_Overflow_Check --
755 -------------------------------------
757 -- This routine is called only if the type is an integer type, and
758 -- a software arithmetic overflow check must be performed for op
759 -- (add, subtract, multiply). The check is performed only if
760 -- Software_Overflow_Checking is enabled and Do_Overflow_Check
761 -- is set. In this case we expand the operation into a more complex
762 -- sequence of tests that ensures that overflow is properly caught.
764 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
765 Loc : constant Source_Ptr := Sloc (N);
766 Typ : constant Entity_Id := Etype (N);
767 Rtyp : constant Entity_Id := Root_Type (Typ);
768 Siz : constant Int := UI_To_Int (Esize (Rtyp));
769 Dsiz : constant Int := Siz * 2;
776 -- Skip this if overflow checks are done in back end, or the overflow
777 -- flag is not set anyway, or we are not doing code expansion.
778 -- Special case CLI target, where arithmetic overflow checks can be
779 -- performed for integer and long_integer
781 if Backend_Overflow_Checks_On_Target
782 or else (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
783 or else not Do_Overflow_Check (N)
784 or else not Expander_Active
789 -- Otherwise, we generate the full general code for front end overflow
790 -- detection, which works by doing arithmetic in a larger type:
796 -- Typ (Checktyp (x) op Checktyp (y));
798 -- where Typ is the type of the original expression, and Checktyp is
799 -- an integer type of sufficient length to hold the largest possible
802 -- In the case where check type exceeds the size of Long_Long_Integer,
803 -- we use a different approach, expanding to:
805 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
807 -- where xxx is Add, Multiply or Subtract as appropriate
809 -- Find check type if one exists
811 if Dsiz <= Standard_Integer_Size then
812 Ctyp := Standard_Integer;
814 elsif Dsiz <= Standard_Long_Long_Integer_Size then
815 Ctyp := Standard_Long_Long_Integer;
817 -- No check type exists, use runtime call
820 if Nkind (N) = N_Op_Add then
821 Cent := RE_Add_With_Ovflo_Check;
823 elsif Nkind (N) = N_Op_Multiply then
824 Cent := RE_Multiply_With_Ovflo_Check;
827 pragma Assert (Nkind (N) = N_Op_Subtract);
828 Cent := RE_Subtract_With_Ovflo_Check;
833 Make_Function_Call (Loc,
834 Name => New_Reference_To (RTE (Cent), Loc),
835 Parameter_Associations => New_List (
836 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
837 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
839 Analyze_And_Resolve (N, Typ);
843 -- If we fall through, we have the case where we do the arithmetic in
844 -- the next higher type and get the check by conversion. In these cases
845 -- Ctyp is set to the type to be used as the check type.
847 Opnod := Relocate_Node (N);
849 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
852 Set_Etype (Opnd, Ctyp);
853 Set_Analyzed (Opnd, True);
854 Set_Left_Opnd (Opnod, Opnd);
856 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
859 Set_Etype (Opnd, Ctyp);
860 Set_Analyzed (Opnd, True);
861 Set_Right_Opnd (Opnod, Opnd);
863 -- The type of the operation changes to the base type of the check type,
864 -- and we reset the overflow check indication, since clearly no overflow
865 -- is possible now that we are using a double length type. We also set
866 -- the Analyzed flag to avoid a recursive attempt to expand the node.
868 Set_Etype (Opnod, Base_Type (Ctyp));
869 Set_Do_Overflow_Check (Opnod, False);
870 Set_Analyzed (Opnod, True);
872 -- Now build the outer conversion
874 Opnd := OK_Convert_To (Typ, Opnod);
876 Set_Etype (Opnd, Typ);
878 -- In the discrete type case, we directly generate the range check for
879 -- the outer operand. This range check will implement the required
882 if Is_Discrete_Type (Typ) then
884 Generate_Range_Check (Expression (N), Typ, CE_Overflow_Check_Failed);
886 -- For other types, we enable overflow checking on the conversion,
887 -- after setting the node as analyzed to prevent recursive attempts
888 -- to expand the conversion node.
891 Set_Analyzed (Opnd, True);
892 Enable_Overflow_Check (Opnd);
897 when RE_Not_Available =>
899 end Apply_Arithmetic_Overflow_Check;
901 ----------------------------
902 -- Apply_Constraint_Check --
903 ----------------------------
905 procedure Apply_Constraint_Check
908 No_Sliding : Boolean := False)
910 Desig_Typ : Entity_Id;
913 if Inside_A_Generic then
916 elsif Is_Scalar_Type (Typ) then
917 Apply_Scalar_Range_Check (N, Typ);
919 elsif Is_Array_Type (Typ) then
921 -- A useful optimization: an aggregate with only an others clause
922 -- always has the right bounds.
924 if Nkind (N) = N_Aggregate
925 and then No (Expressions (N))
927 (First (Choices (First (Component_Associations (N)))))
933 if Is_Constrained (Typ) then
934 Apply_Length_Check (N, Typ);
937 Apply_Range_Check (N, Typ);
940 Apply_Range_Check (N, Typ);
943 elsif (Is_Record_Type (Typ)
944 or else Is_Private_Type (Typ))
945 and then Has_Discriminants (Base_Type (Typ))
946 and then Is_Constrained (Typ)
948 Apply_Discriminant_Check (N, Typ);
950 elsif Is_Access_Type (Typ) then
952 Desig_Typ := Designated_Type (Typ);
954 -- No checks necessary if expression statically null
956 if Known_Null (N) then
957 if Can_Never_Be_Null (Typ) then
958 Install_Null_Excluding_Check (N);
961 -- No sliding possible on access to arrays
963 elsif Is_Array_Type (Desig_Typ) then
964 if Is_Constrained (Desig_Typ) then
965 Apply_Length_Check (N, Typ);
968 Apply_Range_Check (N, Typ);
970 elsif Has_Discriminants (Base_Type (Desig_Typ))
971 and then Is_Constrained (Desig_Typ)
973 Apply_Discriminant_Check (N, Typ);
976 -- Apply the the 2005 Null_Excluding check. Note that we do not apply
977 -- this check if the constraint node is illegal, as shown by having
978 -- an error posted. This additional guard prevents cascaded errors
979 -- and compiler aborts on illegal programs involving Ada 2005 checks.
981 if Can_Never_Be_Null (Typ)
982 and then not Can_Never_Be_Null (Etype (N))
983 and then not Error_Posted (N)
985 Install_Null_Excluding_Check (N);
988 end Apply_Constraint_Check;
990 ------------------------------
991 -- Apply_Discriminant_Check --
992 ------------------------------
994 procedure Apply_Discriminant_Check
997 Lhs : Node_Id := Empty)
999 Loc : constant Source_Ptr := Sloc (N);
1000 Do_Access : constant Boolean := Is_Access_Type (Typ);
1001 S_Typ : Entity_Id := Etype (N);
1005 function Is_Aliased_Unconstrained_Component return Boolean;
1006 -- It is possible for an aliased component to have a nominal
1007 -- unconstrained subtype (through instantiation). If this is a
1008 -- discriminated component assigned in the expansion of an aggregate
1009 -- in an initialization, the check must be suppressed. This unusual
1010 -- situation requires a predicate of its own.
1012 ----------------------------------------
1013 -- Is_Aliased_Unconstrained_Component --
1014 ----------------------------------------
1016 function Is_Aliased_Unconstrained_Component return Boolean is
1021 if Nkind (Lhs) /= N_Selected_Component then
1024 Comp := Entity (Selector_Name (Lhs));
1025 Pref := Prefix (Lhs);
1028 if Ekind (Comp) /= E_Component
1029 or else not Is_Aliased (Comp)
1034 return not Comes_From_Source (Pref)
1035 and then In_Instance
1036 and then not Is_Constrained (Etype (Comp));
1037 end Is_Aliased_Unconstrained_Component;
1039 -- Start of processing for Apply_Discriminant_Check
1043 T_Typ := Designated_Type (Typ);
1048 -- Nothing to do if discriminant checks are suppressed or else no code
1049 -- is to be generated
1051 if not Expander_Active
1052 or else Discriminant_Checks_Suppressed (T_Typ)
1057 -- No discriminant checks necessary for an access when expression is
1058 -- statically Null. This is not only an optimization, it is fundamental
1059 -- because otherwise discriminant checks may be generated in init procs
1060 -- for types containing an access to a not-yet-frozen record, causing a
1061 -- deadly forward reference.
1063 -- Also, if the expression is of an access type whose designated type is
1064 -- incomplete, then the access value must be null and we suppress the
1067 if Known_Null (N) then
1070 elsif Is_Access_Type (S_Typ) then
1071 S_Typ := Designated_Type (S_Typ);
1073 if Ekind (S_Typ) = E_Incomplete_Type then
1078 -- If an assignment target is present, then we need to generate the
1079 -- actual subtype if the target is a parameter or aliased object with
1080 -- an unconstrained nominal subtype.
1082 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1083 -- subtype to the parameter and dereference cases, since other aliased
1084 -- objects are unconstrained (unless the nominal subtype is explicitly
1085 -- constrained). (But we also need to test for renamings???)
1088 and then (Present (Param_Entity (Lhs))
1089 or else (Ada_Version < Ada_05
1090 and then not Is_Constrained (T_Typ)
1091 and then Is_Aliased_View (Lhs)
1092 and then not Is_Aliased_Unconstrained_Component)
1093 or else (Ada_Version >= Ada_05
1094 and then not Is_Constrained (T_Typ)
1095 and then Nkind (Lhs) = N_Explicit_Dereference
1096 and then Nkind (Original_Node (Lhs)) /=
1099 T_Typ := Get_Actual_Subtype (Lhs);
1102 -- Nothing to do if the type is unconstrained (this is the case where
1103 -- the actual subtype in the RM sense of N is unconstrained and no check
1106 if not Is_Constrained (T_Typ) then
1109 -- Ada 2005: nothing to do if the type is one for which there is a
1110 -- partial view that is constrained.
1112 elsif Ada_Version >= Ada_05
1113 and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1118 -- Nothing to do if the type is an Unchecked_Union
1120 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1124 -- Suppress checks if the subtypes are the same. the check must be
1125 -- preserved in an assignment to a formal, because the constraint is
1126 -- given by the actual.
1128 if Nkind (Original_Node (N)) /= N_Allocator
1130 or else not Is_Entity_Name (Lhs)
1131 or else No (Param_Entity (Lhs)))
1134 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1135 and then not Is_Aliased_View (Lhs)
1140 -- We can also eliminate checks on allocators with a subtype mark that
1141 -- coincides with the context type. The context type may be a subtype
1142 -- without a constraint (common case, a generic actual).
1144 elsif Nkind (Original_Node (N)) = N_Allocator
1145 and then Is_Entity_Name (Expression (Original_Node (N)))
1148 Alloc_Typ : constant Entity_Id :=
1149 Entity (Expression (Original_Node (N)));
1152 if Alloc_Typ = T_Typ
1153 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1154 and then Is_Entity_Name (
1155 Subtype_Indication (Parent (T_Typ)))
1156 and then Alloc_Typ = Base_Type (T_Typ))
1164 -- See if we have a case where the types are both constrained, and all
1165 -- the constraints are constants. In this case, we can do the check
1166 -- successfully at compile time.
1168 -- We skip this check for the case where the node is a rewritten`
1169 -- allocator, because it already carries the context subtype, and
1170 -- extracting the discriminants from the aggregate is messy.
1172 if Is_Constrained (S_Typ)
1173 and then Nkind (Original_Node (N)) /= N_Allocator
1183 -- S_Typ may not have discriminants in the case where it is a
1184 -- private type completed by a default discriminated type. In that
1185 -- case, we need to get the constraints from the underlying_type.
1186 -- If the underlying type is unconstrained (i.e. has no default
1187 -- discriminants) no check is needed.
1189 if Has_Discriminants (S_Typ) then
1190 Discr := First_Discriminant (S_Typ);
1191 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1194 Discr := First_Discriminant (Underlying_Type (S_Typ));
1197 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1203 -- A further optimization: if T_Typ is derived from S_Typ
1204 -- without imposing a constraint, no check is needed.
1206 if Nkind (Original_Node (Parent (T_Typ))) =
1207 N_Full_Type_Declaration
1210 Type_Def : constant Node_Id :=
1212 (Original_Node (Parent (T_Typ)));
1214 if Nkind (Type_Def) = N_Derived_Type_Definition
1215 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1216 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1224 DconT := First_Elmt (Discriminant_Constraint (T_Typ));
1226 while Present (Discr) loop
1227 ItemS := Node (DconS);
1228 ItemT := Node (DconT);
1230 -- For a discriminated component type constrained by the
1231 -- current instance of an enclosing type, there is no
1232 -- applicable discriminant check.
1234 if Nkind (ItemT) = N_Attribute_Reference
1235 and then Is_Access_Type (Etype (ItemT))
1236 and then Is_Entity_Name (Prefix (ItemT))
1237 and then Is_Type (Entity (Prefix (ItemT)))
1243 not Is_OK_Static_Expression (ItemS)
1245 not Is_OK_Static_Expression (ItemT);
1247 if Expr_Value (ItemS) /= Expr_Value (ItemT) then
1248 if Do_Access then -- needs run-time check.
1251 Apply_Compile_Time_Constraint_Error
1252 (N, "incorrect value for discriminant&?",
1253 CE_Discriminant_Check_Failed, Ent => Discr);
1260 Next_Discriminant (Discr);
1269 -- Here we need a discriminant check. First build the expression
1270 -- for the comparisons of the discriminants:
1272 -- (n.disc1 /= typ.disc1) or else
1273 -- (n.disc2 /= typ.disc2) or else
1275 -- (n.discn /= typ.discn)
1277 Cond := Build_Discriminant_Checks (N, T_Typ);
1279 -- If Lhs is set and is a parameter, then the condition is
1280 -- guarded by: lhs'constrained and then (condition built above)
1282 if Present (Param_Entity (Lhs)) then
1286 Make_Attribute_Reference (Loc,
1287 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1288 Attribute_Name => Name_Constrained),
1289 Right_Opnd => Cond);
1293 Cond := Guard_Access (Cond, Loc, N);
1297 Make_Raise_Constraint_Error (Loc,
1299 Reason => CE_Discriminant_Check_Failed));
1300 end Apply_Discriminant_Check;
1302 ------------------------
1303 -- Apply_Divide_Check --
1304 ------------------------
1306 procedure Apply_Divide_Check (N : Node_Id) is
1307 Loc : constant Source_Ptr := Sloc (N);
1308 Typ : constant Entity_Id := Etype (N);
1309 Left : constant Node_Id := Left_Opnd (N);
1310 Right : constant Node_Id := Right_Opnd (N);
1322 and then not Backend_Divide_Checks_On_Target
1323 and then Check_Needed (Right, Division_Check)
1325 Determine_Range (Right, ROK, Rlo, Rhi);
1327 -- See if division by zero possible, and if so generate test. This
1328 -- part of the test is not controlled by the -gnato switch.
1330 if Do_Division_Check (N) then
1331 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1333 Make_Raise_Constraint_Error (Loc,
1336 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1337 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1338 Reason => CE_Divide_By_Zero));
1342 -- Test for extremely annoying case of xxx'First divided by -1
1344 if Do_Overflow_Check (N) then
1345 if Nkind (N) = N_Op_Divide
1346 and then Is_Signed_Integer_Type (Typ)
1348 Determine_Range (Left, LOK, Llo, Lhi);
1349 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1351 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1353 ((not LOK) or else (Llo = LLB))
1356 Make_Raise_Constraint_Error (Loc,
1362 Duplicate_Subexpr_Move_Checks (Left),
1363 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1367 Duplicate_Subexpr (Right),
1369 Make_Integer_Literal (Loc, -1))),
1370 Reason => CE_Overflow_Check_Failed));
1375 end Apply_Divide_Check;
1377 ----------------------------------
1378 -- Apply_Float_Conversion_Check --
1379 ----------------------------------
1381 -- Let F and I be the source and target types of the conversion. The RM
1382 -- specifies that a floating-point value X is rounded to the nearest
1383 -- integer, with halfway cases being rounded away from zero. The rounded
1384 -- value of X is checked against I'Range.
1386 -- The catch in the above paragraph is that there is no good way to know
1387 -- whether the round-to-integer operation resulted in overflow. A remedy is
1388 -- to perform a range check in the floating-point domain instead, however:
1390 -- (1) The bounds may not be known at compile time
1391 -- (2) The check must take into account rounding or truncation.
1392 -- (3) The range of type I may not be exactly representable in F.
1393 -- (4) For the rounding case, The end-points I'First - 0.5 and
1394 -- I'Last + 0.5 may or may not be in range, depending on the
1395 -- sign of I'First and I'Last.
1396 -- (5) X may be a NaN, which will fail any comparison
1398 -- The following steps correctly convert X with rounding:
1400 -- (1) If either I'First or I'Last is not known at compile time, use
1401 -- I'Base instead of I in the next three steps and perform a
1402 -- regular range check against I'Range after conversion.
1403 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1404 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1405 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1406 -- In other words, take one of the closest floating-point numbers
1407 -- (which is an integer value) to I'First, and see if it is in
1409 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1410 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1411 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1412 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1413 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1415 -- For the truncating case, replace steps (2) and (3) as follows:
1416 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1417 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1419 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1420 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1423 procedure Apply_Float_Conversion_Check
1425 Target_Typ : Entity_Id)
1427 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1428 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1429 Loc : constant Source_Ptr := Sloc (Ck_Node);
1430 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1431 Target_Base : constant Entity_Id :=
1432 Implementation_Base_Type (Target_Typ);
1434 Par : constant Node_Id := Parent (Ck_Node);
1435 pragma Assert (Nkind (Par) = N_Type_Conversion);
1436 -- Parent of check node, must be a type conversion
1438 Truncate : constant Boolean := Float_Truncate (Par);
1439 Max_Bound : constant Uint :=
1441 (Machine_Radix (Expr_Type),
1442 Machine_Mantissa (Expr_Type) - 1) - 1;
1444 -- Largest bound, so bound plus or minus half is a machine number of F
1446 Ifirst, Ilast : Uint;
1447 -- Bounds of integer type
1450 -- Bounds to check in floating-point domain
1452 Lo_OK, Hi_OK : Boolean;
1453 -- True iff Lo resp. Hi belongs to I'Range
1455 Lo_Chk, Hi_Chk : Node_Id;
1456 -- Expressions that are False iff check fails
1458 Reason : RT_Exception_Code;
1461 if not Compile_Time_Known_Value (LB)
1462 or not Compile_Time_Known_Value (HB)
1465 -- First check that the value falls in the range of the base type,
1466 -- to prevent overflow during conversion and then perform a
1467 -- regular range check against the (dynamic) bounds.
1469 pragma Assert (Target_Base /= Target_Typ);
1471 Temp : constant Entity_Id :=
1472 Make_Defining_Identifier (Loc,
1473 Chars => New_Internal_Name ('T'));
1476 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1477 Set_Etype (Temp, Target_Base);
1479 Insert_Action (Parent (Par),
1480 Make_Object_Declaration (Loc,
1481 Defining_Identifier => Temp,
1482 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1483 Expression => New_Copy_Tree (Par)),
1484 Suppress => All_Checks);
1487 Make_Raise_Constraint_Error (Loc,
1490 Left_Opnd => New_Occurrence_Of (Temp, Loc),
1491 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1492 Reason => CE_Range_Check_Failed));
1493 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1499 -- Get the bounds of the target type
1501 Ifirst := Expr_Value (LB);
1502 Ilast := Expr_Value (HB);
1504 -- Check against lower bound
1506 if Truncate and then Ifirst > 0 then
1507 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1511 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1514 elsif abs (Ifirst) < Max_Bound then
1515 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1516 Lo_OK := (Ifirst > 0);
1519 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1520 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1525 -- Lo_Chk := (X >= Lo)
1527 Lo_Chk := Make_Op_Ge (Loc,
1528 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1529 Right_Opnd => Make_Real_Literal (Loc, Lo));
1532 -- Lo_Chk := (X > Lo)
1534 Lo_Chk := Make_Op_Gt (Loc,
1535 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1536 Right_Opnd => Make_Real_Literal (Loc, Lo));
1539 -- Check against higher bound
1541 if Truncate and then Ilast < 0 then
1542 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1546 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1549 elsif abs (Ilast) < Max_Bound then
1550 Hi := UR_From_Uint (Ilast) + Ureal_Half;
1551 Hi_OK := (Ilast < 0);
1553 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1554 Hi_OK := (Hi <= UR_From_Uint (Ilast));
1559 -- Hi_Chk := (X <= Hi)
1561 Hi_Chk := Make_Op_Le (Loc,
1562 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1563 Right_Opnd => Make_Real_Literal (Loc, Hi));
1566 -- Hi_Chk := (X < Hi)
1568 Hi_Chk := Make_Op_Lt (Loc,
1569 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1570 Right_Opnd => Make_Real_Literal (Loc, Hi));
1573 -- If the bounds of the target type are the same as those of the base
1574 -- type, the check is an overflow check as a range check is not
1575 -- performed in these cases.
1577 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1578 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1580 Reason := CE_Overflow_Check_Failed;
1582 Reason := CE_Range_Check_Failed;
1585 -- Raise CE if either conditions does not hold
1587 Insert_Action (Ck_Node,
1588 Make_Raise_Constraint_Error (Loc,
1589 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1591 end Apply_Float_Conversion_Check;
1593 ------------------------
1594 -- Apply_Length_Check --
1595 ------------------------
1597 procedure Apply_Length_Check
1599 Target_Typ : Entity_Id;
1600 Source_Typ : Entity_Id := Empty)
1603 Apply_Selected_Length_Checks
1604 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1605 end Apply_Length_Check;
1607 -----------------------
1608 -- Apply_Range_Check --
1609 -----------------------
1611 procedure Apply_Range_Check
1613 Target_Typ : Entity_Id;
1614 Source_Typ : Entity_Id := Empty)
1617 Apply_Selected_Range_Checks
1618 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1619 end Apply_Range_Check;
1621 ------------------------------
1622 -- Apply_Scalar_Range_Check --
1623 ------------------------------
1625 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1626 -- off if it is already set on.
1628 procedure Apply_Scalar_Range_Check
1630 Target_Typ : Entity_Id;
1631 Source_Typ : Entity_Id := Empty;
1632 Fixed_Int : Boolean := False)
1634 Parnt : constant Node_Id := Parent (Expr);
1636 Arr : Node_Id := Empty; -- initialize to prevent warning
1637 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
1640 Is_Subscr_Ref : Boolean;
1641 -- Set true if Expr is a subscript
1643 Is_Unconstrained_Subscr_Ref : Boolean;
1644 -- Set true if Expr is a subscript of an unconstrained array. In this
1645 -- case we do not attempt to do an analysis of the value against the
1646 -- range of the subscript, since we don't know the actual subtype.
1649 -- Set to True if Expr should be regarded as a real value even though
1650 -- the type of Expr might be discrete.
1652 procedure Bad_Value;
1653 -- Procedure called if value is determined to be out of range
1659 procedure Bad_Value is
1661 Apply_Compile_Time_Constraint_Error
1662 (Expr, "value not in range of}?", CE_Range_Check_Failed,
1667 -- Start of processing for Apply_Scalar_Range_Check
1670 -- Return if check obviously not needed
1673 -- Not needed inside generic
1677 -- Not needed if previous error
1679 or else Target_Typ = Any_Type
1680 or else Nkind (Expr) = N_Error
1682 -- Not needed for non-scalar type
1684 or else not Is_Scalar_Type (Target_Typ)
1686 -- Not needed if we know node raises CE already
1688 or else Raises_Constraint_Error (Expr)
1693 -- Now, see if checks are suppressed
1696 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1698 if Is_Subscr_Ref then
1699 Arr := Prefix (Parnt);
1700 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1703 if not Do_Range_Check (Expr) then
1705 -- Subscript reference. Check for Index_Checks suppressed
1707 if Is_Subscr_Ref then
1709 -- Check array type and its base type
1711 if Index_Checks_Suppressed (Arr_Typ)
1712 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1716 -- Check array itself if it is an entity name
1718 elsif Is_Entity_Name (Arr)
1719 and then Index_Checks_Suppressed (Entity (Arr))
1723 -- Check expression itself if it is an entity name
1725 elsif Is_Entity_Name (Expr)
1726 and then Index_Checks_Suppressed (Entity (Expr))
1731 -- All other cases, check for Range_Checks suppressed
1734 -- Check target type and its base type
1736 if Range_Checks_Suppressed (Target_Typ)
1737 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1741 -- Check expression itself if it is an entity name
1743 elsif Is_Entity_Name (Expr)
1744 and then Range_Checks_Suppressed (Entity (Expr))
1748 -- If Expr is part of an assignment statement, then check left
1749 -- side of assignment if it is an entity name.
1751 elsif Nkind (Parnt) = N_Assignment_Statement
1752 and then Is_Entity_Name (Name (Parnt))
1753 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1760 -- Do not set range checks if they are killed
1762 if Nkind (Expr) = N_Unchecked_Type_Conversion
1763 and then Kill_Range_Check (Expr)
1768 -- Do not set range checks for any values from System.Scalar_Values
1769 -- since the whole idea of such values is to avoid checking them!
1771 if Is_Entity_Name (Expr)
1772 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1777 -- Now see if we need a check
1779 if No (Source_Typ) then
1780 S_Typ := Etype (Expr);
1782 S_Typ := Source_Typ;
1785 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1789 Is_Unconstrained_Subscr_Ref :=
1790 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1792 -- Always do a range check if the source type includes infinities and
1793 -- the target type does not include infinities. We do not do this if
1794 -- range checks are killed.
1796 if Is_Floating_Point_Type (S_Typ)
1797 and then Has_Infinities (S_Typ)
1798 and then not Has_Infinities (Target_Typ)
1800 Enable_Range_Check (Expr);
1803 -- Return if we know expression is definitely in the range of the target
1804 -- type as determined by Determine_Range. Right now we only do this for
1805 -- discrete types, and not fixed-point or floating-point types.
1807 -- The additional less-precise tests below catch these cases
1809 -- Note: skip this if we are given a source_typ, since the point of
1810 -- supplying a Source_Typ is to stop us looking at the expression.
1811 -- We could sharpen this test to be out parameters only ???
1813 if Is_Discrete_Type (Target_Typ)
1814 and then Is_Discrete_Type (Etype (Expr))
1815 and then not Is_Unconstrained_Subscr_Ref
1816 and then No (Source_Typ)
1819 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
1820 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1825 if Compile_Time_Known_Value (Tlo)
1826 and then Compile_Time_Known_Value (Thi)
1829 Lov : constant Uint := Expr_Value (Tlo);
1830 Hiv : constant Uint := Expr_Value (Thi);
1833 -- If range is null, we for sure have a constraint error
1834 -- (we don't even need to look at the value involved,
1835 -- since all possible values will raise CE).
1842 -- Otherwise determine range of value
1844 Determine_Range (Expr, OK, Lo, Hi);
1848 -- If definitely in range, all OK
1850 if Lo >= Lov and then Hi <= Hiv then
1853 -- If definitely not in range, warn
1855 elsif Lov > Hi or else Hiv < Lo then
1859 -- Otherwise we don't know
1871 Is_Floating_Point_Type (S_Typ)
1872 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
1874 -- Check if we can determine at compile time whether Expr is in the
1875 -- range of the target type. Note that if S_Typ is within the bounds
1876 -- of Target_Typ then this must be the case. This check is meaningful
1877 -- only if this is not a conversion between integer and real types.
1879 if not Is_Unconstrained_Subscr_Ref
1881 Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
1883 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
1885 Is_In_Range (Expr, Target_Typ, Fixed_Int, Int_Real))
1889 elsif Is_Out_Of_Range (Expr, Target_Typ, Fixed_Int, Int_Real) then
1893 -- In the floating-point case, we only do range checks if the type is
1894 -- constrained. We definitely do NOT want range checks for unconstrained
1895 -- types, since we want to have infinities
1897 elsif Is_Floating_Point_Type (S_Typ) then
1898 if Is_Constrained (S_Typ) then
1899 Enable_Range_Check (Expr);
1902 -- For all other cases we enable a range check unconditionally
1905 Enable_Range_Check (Expr);
1908 end Apply_Scalar_Range_Check;
1910 ----------------------------------
1911 -- Apply_Selected_Length_Checks --
1912 ----------------------------------
1914 procedure Apply_Selected_Length_Checks
1916 Target_Typ : Entity_Id;
1917 Source_Typ : Entity_Id;
1918 Do_Static : Boolean)
1921 R_Result : Check_Result;
1924 Loc : constant Source_Ptr := Sloc (Ck_Node);
1925 Checks_On : constant Boolean :=
1926 (not Index_Checks_Suppressed (Target_Typ))
1928 (not Length_Checks_Suppressed (Target_Typ));
1931 if not Expander_Active then
1936 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
1938 for J in 1 .. 2 loop
1939 R_Cno := R_Result (J);
1940 exit when No (R_Cno);
1942 -- A length check may mention an Itype which is attached to a
1943 -- subsequent node. At the top level in a package this can cause
1944 -- an order-of-elaboration problem, so we make sure that the itype
1945 -- is referenced now.
1947 if Ekind (Current_Scope) = E_Package
1948 and then Is_Compilation_Unit (Current_Scope)
1950 Ensure_Defined (Target_Typ, Ck_Node);
1952 if Present (Source_Typ) then
1953 Ensure_Defined (Source_Typ, Ck_Node);
1955 elsif Is_Itype (Etype (Ck_Node)) then
1956 Ensure_Defined (Etype (Ck_Node), Ck_Node);
1960 -- If the item is a conditional raise of constraint error, then have
1961 -- a look at what check is being performed and ???
1963 if Nkind (R_Cno) = N_Raise_Constraint_Error
1964 and then Present (Condition (R_Cno))
1966 Cond := Condition (R_Cno);
1968 -- Case where node does not now have a dynamic check
1970 if not Has_Dynamic_Length_Check (Ck_Node) then
1972 -- If checks are on, just insert the check
1975 Insert_Action (Ck_Node, R_Cno);
1977 if not Do_Static then
1978 Set_Has_Dynamic_Length_Check (Ck_Node);
1981 -- If checks are off, then analyze the length check after
1982 -- temporarily attaching it to the tree in case the relevant
1983 -- condition can be evaluted at compile time. We still want a
1984 -- compile time warning in this case.
1987 Set_Parent (R_Cno, Ck_Node);
1992 -- Output a warning if the condition is known to be True
1994 if Is_Entity_Name (Cond)
1995 and then Entity (Cond) = Standard_True
1997 Apply_Compile_Time_Constraint_Error
1998 (Ck_Node, "wrong length for array of}?",
1999 CE_Length_Check_Failed,
2003 -- If we were only doing a static check, or if checks are not
2004 -- on, then we want to delete the check, since it is not needed.
2005 -- We do this by replacing the if statement by a null statement
2007 elsif Do_Static or else not Checks_On then
2008 Remove_Warning_Messages (R_Cno);
2009 Rewrite (R_Cno, Make_Null_Statement (Loc));
2013 Install_Static_Check (R_Cno, Loc);
2016 end Apply_Selected_Length_Checks;
2018 ---------------------------------
2019 -- Apply_Selected_Range_Checks --
2020 ---------------------------------
2022 procedure Apply_Selected_Range_Checks
2024 Target_Typ : Entity_Id;
2025 Source_Typ : Entity_Id;
2026 Do_Static : Boolean)
2029 R_Result : Check_Result;
2032 Loc : constant Source_Ptr := Sloc (Ck_Node);
2033 Checks_On : constant Boolean :=
2034 (not Index_Checks_Suppressed (Target_Typ))
2036 (not Range_Checks_Suppressed (Target_Typ));
2039 if not Expander_Active or else not Checks_On then
2044 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2046 for J in 1 .. 2 loop
2048 R_Cno := R_Result (J);
2049 exit when No (R_Cno);
2051 -- If the item is a conditional raise of constraint error, then have
2052 -- a look at what check is being performed and ???
2054 if Nkind (R_Cno) = N_Raise_Constraint_Error
2055 and then Present (Condition (R_Cno))
2057 Cond := Condition (R_Cno);
2059 if not Has_Dynamic_Range_Check (Ck_Node) then
2060 Insert_Action (Ck_Node, R_Cno);
2062 if not Do_Static then
2063 Set_Has_Dynamic_Range_Check (Ck_Node);
2067 -- Output a warning if the condition is known to be True
2069 if Is_Entity_Name (Cond)
2070 and then Entity (Cond) = Standard_True
2072 -- Since an N_Range is technically not an expression, we have
2073 -- to set one of the bounds to C_E and then just flag the
2074 -- N_Range. The warning message will point to the lower bound
2075 -- and complain about a range, which seems OK.
2077 if Nkind (Ck_Node) = N_Range then
2078 Apply_Compile_Time_Constraint_Error
2079 (Low_Bound (Ck_Node), "static range out of bounds of}?",
2080 CE_Range_Check_Failed,
2084 Set_Raises_Constraint_Error (Ck_Node);
2087 Apply_Compile_Time_Constraint_Error
2088 (Ck_Node, "static value out of range of}?",
2089 CE_Range_Check_Failed,
2094 -- If we were only doing a static check, or if checks are not
2095 -- on, then we want to delete the check, since it is not needed.
2096 -- We do this by replacing the if statement by a null statement
2098 elsif Do_Static or else not Checks_On then
2099 Remove_Warning_Messages (R_Cno);
2100 Rewrite (R_Cno, Make_Null_Statement (Loc));
2104 Install_Static_Check (R_Cno, Loc);
2107 end Apply_Selected_Range_Checks;
2109 -------------------------------
2110 -- Apply_Static_Length_Check --
2111 -------------------------------
2113 procedure Apply_Static_Length_Check
2115 Target_Typ : Entity_Id;
2116 Source_Typ : Entity_Id := Empty)
2119 Apply_Selected_Length_Checks
2120 (Expr, Target_Typ, Source_Typ, Do_Static => True);
2121 end Apply_Static_Length_Check;
2123 -------------------------------------
2124 -- Apply_Subscript_Validity_Checks --
2125 -------------------------------------
2127 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2131 pragma Assert (Nkind (Expr) = N_Indexed_Component);
2133 -- Loop through subscripts
2135 Sub := First (Expressions (Expr));
2136 while Present (Sub) loop
2138 -- Check one subscript. Note that we do not worry about enumeration
2139 -- type with holes, since we will convert the value to a Pos value
2140 -- for the subscript, and that convert will do the necessary validity
2143 Ensure_Valid (Sub, Holes_OK => True);
2145 -- Move to next subscript
2149 end Apply_Subscript_Validity_Checks;
2151 ----------------------------------
2152 -- Apply_Type_Conversion_Checks --
2153 ----------------------------------
2155 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2156 Target_Type : constant Entity_Id := Etype (N);
2157 Target_Base : constant Entity_Id := Base_Type (Target_Type);
2158 Expr : constant Node_Id := Expression (N);
2159 Expr_Type : constant Entity_Id := Etype (Expr);
2162 if Inside_A_Generic then
2165 -- Skip these checks if serious errors detected, there are some nasty
2166 -- situations of incomplete trees that blow things up.
2168 elsif Serious_Errors_Detected > 0 then
2171 -- Scalar type conversions of the form Target_Type (Expr) require a
2172 -- range check if we cannot be sure that Expr is in the base type of
2173 -- Target_Typ and also that Expr is in the range of Target_Typ. These
2174 -- are not quite the same condition from an implementation point of
2175 -- view, but clearly the second includes the first.
2177 elsif Is_Scalar_Type (Target_Type) then
2179 Conv_OK : constant Boolean := Conversion_OK (N);
2180 -- If the Conversion_OK flag on the type conversion is set and no
2181 -- floating point type is involved in the type conversion then
2182 -- fixed point values must be read as integral values.
2184 Float_To_Int : constant Boolean :=
2185 Is_Floating_Point_Type (Expr_Type)
2186 and then Is_Integer_Type (Target_Type);
2189 if not Overflow_Checks_Suppressed (Target_Base)
2190 and then not In_Subrange_Of (Expr_Type, Target_Base, Conv_OK)
2191 and then not Float_To_Int
2193 Activate_Overflow_Check (N);
2196 if not Range_Checks_Suppressed (Target_Type)
2197 and then not Range_Checks_Suppressed (Expr_Type)
2199 if Float_To_Int then
2200 Apply_Float_Conversion_Check (Expr, Target_Type);
2202 Apply_Scalar_Range_Check
2203 (Expr, Target_Type, Fixed_Int => Conv_OK);
2208 elsif Comes_From_Source (N)
2209 and then Is_Record_Type (Target_Type)
2210 and then Is_Derived_Type (Target_Type)
2211 and then not Is_Tagged_Type (Target_Type)
2212 and then not Is_Constrained (Target_Type)
2213 and then Present (Stored_Constraint (Target_Type))
2215 -- An unconstrained derived type may have inherited discriminant
2216 -- Build an actual discriminant constraint list using the stored
2217 -- constraint, to verify that the expression of the parent type
2218 -- satisfies the constraints imposed by the (unconstrained!)
2219 -- derived type. This applies to value conversions, not to view
2220 -- conversions of tagged types.
2223 Loc : constant Source_Ptr := Sloc (N);
2225 Constraint : Elmt_Id;
2226 Discr_Value : Node_Id;
2229 New_Constraints : constant Elist_Id := New_Elmt_List;
2230 Old_Constraints : constant Elist_Id :=
2231 Discriminant_Constraint (Expr_Type);
2234 Constraint := First_Elmt (Stored_Constraint (Target_Type));
2235 while Present (Constraint) loop
2236 Discr_Value := Node (Constraint);
2238 if Is_Entity_Name (Discr_Value)
2239 and then Ekind (Entity (Discr_Value)) = E_Discriminant
2241 Discr := Corresponding_Discriminant (Entity (Discr_Value));
2244 and then Scope (Discr) = Base_Type (Expr_Type)
2246 -- Parent is constrained by new discriminant. Obtain
2247 -- Value of original discriminant in expression. If the
2248 -- new discriminant has been used to constrain more than
2249 -- one of the stored discriminants, this will provide the
2250 -- required consistency check.
2253 Make_Selected_Component (Loc,
2255 Duplicate_Subexpr_No_Checks
2256 (Expr, Name_Req => True),
2258 Make_Identifier (Loc, Chars (Discr))),
2262 -- Discriminant of more remote ancestor ???
2267 -- Derived type definition has an explicit value for this
2268 -- stored discriminant.
2272 (Duplicate_Subexpr_No_Checks (Discr_Value),
2276 Next_Elmt (Constraint);
2279 -- Use the unconstrained expression type to retrieve the
2280 -- discriminants of the parent, and apply momentarily the
2281 -- discriminant constraint synthesized above.
2283 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2284 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2285 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2288 Make_Raise_Constraint_Error (Loc,
2290 Reason => CE_Discriminant_Check_Failed));
2293 -- For arrays, conversions are applied during expansion, to take into
2294 -- accounts changes of representation. The checks become range checks on
2295 -- the base type or length checks on the subtype, depending on whether
2296 -- the target type is unconstrained or constrained.
2301 end Apply_Type_Conversion_Checks;
2303 ----------------------------------------------
2304 -- Apply_Universal_Integer_Attribute_Checks --
2305 ----------------------------------------------
2307 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2308 Loc : constant Source_Ptr := Sloc (N);
2309 Typ : constant Entity_Id := Etype (N);
2312 if Inside_A_Generic then
2315 -- Nothing to do if checks are suppressed
2317 elsif Range_Checks_Suppressed (Typ)
2318 and then Overflow_Checks_Suppressed (Typ)
2322 -- Nothing to do if the attribute does not come from source. The
2323 -- internal attributes we generate of this type do not need checks,
2324 -- and furthermore the attempt to check them causes some circular
2325 -- elaboration orders when dealing with packed types.
2327 elsif not Comes_From_Source (N) then
2330 -- If the prefix is a selected component that depends on a discriminant
2331 -- the check may improperly expose a discriminant instead of using
2332 -- the bounds of the object itself. Set the type of the attribute to
2333 -- the base type of the context, so that a check will be imposed when
2334 -- needed (e.g. if the node appears as an index).
2336 elsif Nkind (Prefix (N)) = N_Selected_Component
2337 and then Ekind (Typ) = E_Signed_Integer_Subtype
2338 and then Depends_On_Discriminant (Scalar_Range (Typ))
2340 Set_Etype (N, Base_Type (Typ));
2342 -- Otherwise, replace the attribute node with a type conversion node
2343 -- whose expression is the attribute, retyped to universal integer, and
2344 -- whose subtype mark is the target type. The call to analyze this
2345 -- conversion will set range and overflow checks as required for proper
2346 -- detection of an out of range value.
2349 Set_Etype (N, Universal_Integer);
2350 Set_Analyzed (N, True);
2353 Make_Type_Conversion (Loc,
2354 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2355 Expression => Relocate_Node (N)));
2357 Analyze_And_Resolve (N, Typ);
2361 end Apply_Universal_Integer_Attribute_Checks;
2363 -------------------------------
2364 -- Build_Discriminant_Checks --
2365 -------------------------------
2367 function Build_Discriminant_Checks
2369 T_Typ : Entity_Id) return Node_Id
2371 Loc : constant Source_Ptr := Sloc (N);
2374 Disc_Ent : Entity_Id;
2378 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2380 ----------------------------------
2381 -- Aggregate_Discriminant_Value --
2382 ----------------------------------
2384 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2388 -- The aggregate has been normalized with named associations. We use
2389 -- the Chars field to locate the discriminant to take into account
2390 -- discriminants in derived types, which carry the same name as those
2393 Assoc := First (Component_Associations (N));
2394 while Present (Assoc) loop
2395 if Chars (First (Choices (Assoc))) = Chars (Disc) then
2396 return Expression (Assoc);
2402 -- Discriminant must have been found in the loop above
2404 raise Program_Error;
2405 end Aggregate_Discriminant_Val;
2407 -- Start of processing for Build_Discriminant_Checks
2410 -- Loop through discriminants evolving the condition
2413 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2415 -- For a fully private type, use the discriminants of the parent type
2417 if Is_Private_Type (T_Typ)
2418 and then No (Full_View (T_Typ))
2420 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2422 Disc_Ent := First_Discriminant (T_Typ);
2425 while Present (Disc) loop
2426 Dval := Node (Disc);
2428 if Nkind (Dval) = N_Identifier
2429 and then Ekind (Entity (Dval)) = E_Discriminant
2431 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2433 Dval := Duplicate_Subexpr_No_Checks (Dval);
2436 -- If we have an Unchecked_Union node, we can infer the discriminants
2439 if Is_Unchecked_Union (Base_Type (T_Typ)) then
2441 Get_Discriminant_Value (
2442 First_Discriminant (T_Typ),
2444 Stored_Constraint (T_Typ)));
2446 elsif Nkind (N) = N_Aggregate then
2448 Duplicate_Subexpr_No_Checks
2449 (Aggregate_Discriminant_Val (Disc_Ent));
2453 Make_Selected_Component (Loc,
2455 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2457 Make_Identifier (Loc, Chars (Disc_Ent)));
2459 Set_Is_In_Discriminant_Check (Dref);
2462 Evolve_Or_Else (Cond,
2465 Right_Opnd => Dval));
2468 Next_Discriminant (Disc_Ent);
2472 end Build_Discriminant_Checks;
2478 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2486 -- Always check if not simple entity
2488 if Nkind (Nod) not in N_Has_Entity
2489 or else not Comes_From_Source (Nod)
2494 -- Look up tree for short circuit
2501 if K not in N_Subexpr then
2504 -- Or/Or Else case, left operand must be equality test
2506 elsif K = N_Op_Or or else K = N_Or_Else then
2507 exit when N = Right_Opnd (P)
2508 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2510 -- And/And then case, left operand must be inequality test
2512 elsif K = N_Op_And or else K = N_And_Then then
2513 exit when N = Right_Opnd (P)
2514 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2520 -- If we fall through the loop, then we have a conditional with an
2521 -- appropriate test as its left operand. So test further.
2525 if Nkind (L) = N_Op_Not then
2526 L := Right_Opnd (L);
2529 R := Right_Opnd (L);
2532 -- Left operand of test must match original variable
2534 if Nkind (L) not in N_Has_Entity
2535 or else Entity (L) /= Entity (Nod)
2540 -- Right operand of test must be key value (zero or null)
2543 when Access_Check =>
2544 if not Known_Null (R) then
2548 when Division_Check =>
2549 if not Compile_Time_Known_Value (R)
2550 or else Expr_Value (R) /= Uint_0
2556 raise Program_Error;
2559 -- Here we have the optimizable case, warn if not short-circuited
2561 if K = N_Op_And or else K = N_Op_Or then
2563 when Access_Check =>
2565 ("Constraint_Error may be raised (access check)?",
2567 when Division_Check =>
2569 ("Constraint_Error may be raised (zero divide)?",
2573 raise Program_Error;
2576 if K = N_Op_And then
2577 Error_Msg_N ("use `AND THEN` instead of AND?", P);
2579 Error_Msg_N ("use `OR ELSE` instead of OR?", P);
2582 -- If not short-circuited, we need the ckeck
2586 -- If short-circuited, we can omit the check
2593 -----------------------------------
2594 -- Check_Valid_Lvalue_Subscripts --
2595 -----------------------------------
2597 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2599 -- Skip this if range checks are suppressed
2601 if Range_Checks_Suppressed (Etype (Expr)) then
2604 -- Only do this check for expressions that come from source. We assume
2605 -- that expander generated assignments explicitly include any necessary
2606 -- checks. Note that this is not just an optimization, it avoids
2607 -- infinite recursions!
2609 elsif not Comes_From_Source (Expr) then
2612 -- For a selected component, check the prefix
2614 elsif Nkind (Expr) = N_Selected_Component then
2615 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2618 -- Case of indexed component
2620 elsif Nkind (Expr) = N_Indexed_Component then
2621 Apply_Subscript_Validity_Checks (Expr);
2623 -- Prefix may itself be or contain an indexed component, and these
2624 -- subscripts need checking as well.
2626 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2628 end Check_Valid_Lvalue_Subscripts;
2630 ----------------------------------
2631 -- Null_Exclusion_Static_Checks --
2632 ----------------------------------
2634 procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2635 Error_Node : Node_Id;
2637 Has_Null : constant Boolean := Has_Null_Exclusion (N);
2638 K : constant Node_Kind := Nkind (N);
2643 (K = N_Component_Declaration
2644 or else K = N_Discriminant_Specification
2645 or else K = N_Function_Specification
2646 or else K = N_Object_Declaration
2647 or else K = N_Parameter_Specification);
2649 if K = N_Function_Specification then
2650 Typ := Etype (Defining_Entity (N));
2652 Typ := Etype (Defining_Identifier (N));
2656 when N_Component_Declaration =>
2657 if Present (Access_Definition (Component_Definition (N))) then
2658 Error_Node := Component_Definition (N);
2660 Error_Node := Subtype_Indication (Component_Definition (N));
2663 when N_Discriminant_Specification =>
2664 Error_Node := Discriminant_Type (N);
2666 when N_Function_Specification =>
2667 Error_Node := Result_Definition (N);
2669 when N_Object_Declaration =>
2670 Error_Node := Object_Definition (N);
2672 when N_Parameter_Specification =>
2673 Error_Node := Parameter_Type (N);
2676 raise Program_Error;
2681 -- Enforce legality rule 3.10 (13): A null exclusion can only be
2682 -- applied to an access [sub]type.
2684 if not Is_Access_Type (Typ) then
2686 ("`NOT NULL` allowed only for an access type", Error_Node);
2688 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
2689 -- be applied to a [sub]type that does not exclude null already.
2691 elsif Can_Never_Be_Null (Typ)
2693 -- No need to check itypes that have a null exclusion because
2694 -- they are already examined at their point of creation.
2696 and then not Is_Itype (Typ)
2699 ("`NOT NULL` not allowed (& already excludes null)",
2704 -- Check that null-excluding objects are always initialized
2706 if K = N_Object_Declaration
2707 and then No (Expression (N))
2708 and then not No_Initialization (N)
2710 -- Add an expression that assigns null. This node is needed by
2711 -- Apply_Compile_Time_Constraint_Error, which will replace this with
2712 -- a Constraint_Error node.
2714 Set_Expression (N, Make_Null (Sloc (N)));
2715 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2717 Apply_Compile_Time_Constraint_Error
2718 (N => Expression (N),
2719 Msg => "(Ada 2005) null-excluding objects must be initialized?",
2720 Reason => CE_Null_Not_Allowed);
2723 -- Check that a null-excluding component, formal or object is not
2724 -- being assigned a null value. Otherwise generate a warning message
2725 -- and replace Expression (N) by a N_Contraint_Error node.
2727 if K /= N_Function_Specification then
2728 Expr := Expression (N);
2730 if Present (Expr) and then Known_Null (Expr) then
2732 when N_Component_Declaration |
2733 N_Discriminant_Specification =>
2734 Apply_Compile_Time_Constraint_Error
2736 Msg => "(Ada 2005) null not allowed " &
2737 "in null-excluding components?",
2738 Reason => CE_Null_Not_Allowed);
2740 when N_Object_Declaration =>
2741 Apply_Compile_Time_Constraint_Error
2743 Msg => "(Ada 2005) null not allowed " &
2744 "in null-excluding objects?",
2745 Reason => CE_Null_Not_Allowed);
2747 when N_Parameter_Specification =>
2748 Apply_Compile_Time_Constraint_Error
2750 Msg => "(Ada 2005) null not allowed " &
2751 "in null-excluding formals?",
2752 Reason => CE_Null_Not_Allowed);
2759 end Null_Exclusion_Static_Checks;
2761 ----------------------------------
2762 -- Conditional_Statements_Begin --
2763 ----------------------------------
2765 procedure Conditional_Statements_Begin is
2767 Saved_Checks_TOS := Saved_Checks_TOS + 1;
2769 -- If stack overflows, kill all checks, that way we know to simply reset
2770 -- the number of saved checks to zero on return. This should never occur
2773 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2776 -- In the normal case, we just make a new stack entry saving the current
2777 -- number of saved checks for a later restore.
2780 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2782 if Debug_Flag_CC then
2783 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2787 end Conditional_Statements_Begin;
2789 --------------------------------
2790 -- Conditional_Statements_End --
2791 --------------------------------
2793 procedure Conditional_Statements_End is
2795 pragma Assert (Saved_Checks_TOS > 0);
2797 -- If the saved checks stack overflowed, then we killed all checks, so
2798 -- setting the number of saved checks back to zero is correct. This
2799 -- should never occur in practice.
2801 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2802 Num_Saved_Checks := 0;
2804 -- In the normal case, restore the number of saved checks from the top
2808 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
2809 if Debug_Flag_CC then
2810 w ("Conditional_Statements_End: Num_Saved_Checks = ",
2815 Saved_Checks_TOS := Saved_Checks_TOS - 1;
2816 end Conditional_Statements_End;
2818 ---------------------
2819 -- Determine_Range --
2820 ---------------------
2822 Cache_Size : constant := 2 ** 10;
2823 type Cache_Index is range 0 .. Cache_Size - 1;
2824 -- Determine size of below cache (power of 2 is more efficient!)
2826 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
2827 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
2828 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
2829 -- The above arrays are used to implement a small direct cache for
2830 -- Determine_Range calls. Because of the way Determine_Range recursively
2831 -- traces subexpressions, and because overflow checking calls the routine
2832 -- on the way up the tree, a quadratic behavior can otherwise be
2833 -- encountered in large expressions. The cache entry for node N is stored
2834 -- in the (N mod Cache_Size) entry, and can be validated by checking the
2835 -- actual node value stored there.
2837 procedure Determine_Range
2843 Typ : constant Entity_Id := Etype (N);
2847 -- Lo and Hi bounds of left operand
2851 -- Lo and Hi bounds of right (or only) operand
2854 -- Temp variable used to hold a bound node
2857 -- High bound of base type of expression
2861 -- Refined values for low and high bounds, after tightening
2864 -- Used in lower level calls to indicate if call succeeded
2866 Cindex : Cache_Index;
2867 -- Used to search cache
2869 function OK_Operands return Boolean;
2870 -- Used for binary operators. Determines the ranges of the left and
2871 -- right operands, and if they are both OK, returns True, and puts
2872 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left
2878 function OK_Operands return Boolean is
2880 Determine_Range (Left_Opnd (N), OK1, Lo_Left, Hi_Left);
2886 Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
2890 -- Start of processing for Determine_Range
2893 -- Prevent junk warnings by initializing range variables
2900 -- If the type is not discrete, or is undefined, then we can't do
2901 -- anything about determining the range.
2903 if No (Typ) or else not Is_Discrete_Type (Typ)
2904 or else Error_Posted (N)
2910 -- For all other cases, we can determine the range
2914 -- If value is compile time known, then the possible range is the one
2915 -- value that we know this expression definitely has!
2917 if Compile_Time_Known_Value (N) then
2918 Lo := Expr_Value (N);
2923 -- Return if already in the cache
2925 Cindex := Cache_Index (N mod Cache_Size);
2927 if Determine_Range_Cache_N (Cindex) = N then
2928 Lo := Determine_Range_Cache_Lo (Cindex);
2929 Hi := Determine_Range_Cache_Hi (Cindex);
2933 -- Otherwise, start by finding the bounds of the type of the expression,
2934 -- the value cannot be outside this range (if it is, then we have an
2935 -- overflow situation, which is a separate check, we are talking here
2936 -- only about the expression value).
2938 -- We use the actual bound unless it is dynamic, in which case use the
2939 -- corresponding base type bound if possible. If we can't get a bound
2940 -- then we figure we can't determine the range (a peculiar case, that
2941 -- perhaps cannot happen, but there is no point in bombing in this
2942 -- optimization circuit.
2944 -- First the low bound
2946 Bound := Type_Low_Bound (Typ);
2948 if Compile_Time_Known_Value (Bound) then
2949 Lo := Expr_Value (Bound);
2951 elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
2952 Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
2959 -- Now the high bound
2961 Bound := Type_High_Bound (Typ);
2963 -- We need the high bound of the base type later on, and this should
2964 -- always be compile time known. Again, it is not clear that this
2965 -- can ever be false, but no point in bombing.
2967 if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
2968 Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
2976 -- If we have a static subtype, then that may have a tighter bound so
2977 -- use the upper bound of the subtype instead in this case.
2979 if Compile_Time_Known_Value (Bound) then
2980 Hi := Expr_Value (Bound);
2983 -- We may be able to refine this value in certain situations. If any
2984 -- refinement is possible, then Lor and Hir are set to possibly tighter
2985 -- bounds, and OK1 is set to True.
2989 -- For unary plus, result is limited by range of operand
2992 Determine_Range (Right_Opnd (N), OK1, Lor, Hir);
2994 -- For unary minus, determine range of operand, and negate it
2997 Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
3004 -- For binary addition, get range of each operand and do the
3005 -- addition to get the result range.
3009 Lor := Lo_Left + Lo_Right;
3010 Hir := Hi_Left + Hi_Right;
3013 -- Division is tricky. The only case we consider is where the right
3014 -- operand is a positive constant, and in this case we simply divide
3015 -- the bounds of the left operand
3019 if Lo_Right = Hi_Right
3020 and then Lo_Right > 0
3022 Lor := Lo_Left / Lo_Right;
3023 Hir := Hi_Left / Lo_Right;
3030 -- For binary subtraction, get range of each operand and do the worst
3031 -- case subtraction to get the result range.
3033 when N_Op_Subtract =>
3035 Lor := Lo_Left - Hi_Right;
3036 Hir := Hi_Left - Lo_Right;
3039 -- For MOD, if right operand is a positive constant, then result must
3040 -- be in the allowable range of mod results.
3044 if Lo_Right = Hi_Right
3045 and then Lo_Right /= 0
3047 if Lo_Right > 0 then
3049 Hir := Lo_Right - 1;
3051 else -- Lo_Right < 0
3052 Lor := Lo_Right + 1;
3061 -- For REM, if right operand is a positive constant, then result must
3062 -- be in the allowable range of mod results.
3066 if Lo_Right = Hi_Right
3067 and then Lo_Right /= 0
3070 Dval : constant Uint := (abs Lo_Right) - 1;
3073 -- The sign of the result depends on the sign of the
3074 -- dividend (but not on the sign of the divisor, hence
3075 -- the abs operation above).
3095 -- Attribute reference cases
3097 when N_Attribute_Reference =>
3098 case Attribute_Name (N) is
3100 -- For Pos/Val attributes, we can refine the range using the
3101 -- possible range of values of the attribute expression
3103 when Name_Pos | Name_Val =>
3104 Determine_Range (First (Expressions (N)), OK1, Lor, Hir);
3106 -- For Length attribute, use the bounds of the corresponding
3107 -- index type to refine the range.
3111 Atyp : Entity_Id := Etype (Prefix (N));
3119 if Is_Access_Type (Atyp) then
3120 Atyp := Designated_Type (Atyp);
3123 -- For string literal, we know exact value
3125 if Ekind (Atyp) = E_String_Literal_Subtype then
3127 Lo := String_Literal_Length (Atyp);
3128 Hi := String_Literal_Length (Atyp);
3132 -- Otherwise check for expression given
3134 if No (Expressions (N)) then
3138 UI_To_Int (Expr_Value (First (Expressions (N))));
3141 Indx := First_Index (Atyp);
3142 for J in 2 .. Inum loop
3143 Indx := Next_Index (Indx);
3147 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU);
3151 (Type_High_Bound (Etype (Indx)), OK1, UL, UU);
3155 -- The maximum value for Length is the biggest
3156 -- possible gap between the values of the bounds.
3157 -- But of course, this value cannot be negative.
3159 Hir := UI_Max (Uint_0, UU - LL);
3161 -- For constrained arrays, the minimum value for
3162 -- Length is taken from the actual value of the
3163 -- bounds, since the index will be exactly of
3166 if Is_Constrained (Atyp) then
3167 Lor := UI_Max (Uint_0, UL - LU);
3169 -- For an unconstrained array, the minimum value
3170 -- for length is always zero.
3179 -- No special handling for other attributes
3180 -- Probably more opportunities exist here ???
3187 -- For type conversion from one discrete type to another, we can
3188 -- refine the range using the converted value.
3190 when N_Type_Conversion =>
3191 Determine_Range (Expression (N), OK1, Lor, Hir);
3193 -- Nothing special to do for all other expression kinds
3201 -- At this stage, if OK1 is true, then we know that the actual
3202 -- result of the computed expression is in the range Lor .. Hir.
3203 -- We can use this to restrict the possible range of results.
3207 -- If the refined value of the low bound is greater than the
3208 -- type high bound, then reset it to the more restrictive
3209 -- value. However, we do NOT do this for the case of a modular
3210 -- type where the possible upper bound on the value is above the
3211 -- base type high bound, because that means the result could wrap.
3214 and then not (Is_Modular_Integer_Type (Typ)
3215 and then Hir > Hbound)
3220 -- Similarly, if the refined value of the high bound is less
3221 -- than the value so far, then reset it to the more restrictive
3222 -- value. Again, we do not do this if the refined low bound is
3223 -- negative for a modular type, since this would wrap.
3226 and then not (Is_Modular_Integer_Type (Typ)
3227 and then Lor < Uint_0)
3233 -- Set cache entry for future call and we are all done
3235 Determine_Range_Cache_N (Cindex) := N;
3236 Determine_Range_Cache_Lo (Cindex) := Lo;
3237 Determine_Range_Cache_Hi (Cindex) := Hi;
3240 -- If any exception occurs, it means that we have some bug in the compiler
3241 -- possibly triggered by a previous error, or by some unforseen peculiar
3242 -- occurrence. However, this is only an optimization attempt, so there is
3243 -- really no point in crashing the compiler. Instead we just decide, too
3244 -- bad, we can't figure out a range in this case after all.
3249 -- Debug flag K disables this behavior (useful for debugging)
3251 if Debug_Flag_K then
3259 end Determine_Range;
3261 ------------------------------------
3262 -- Discriminant_Checks_Suppressed --
3263 ------------------------------------
3265 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3268 if Is_Unchecked_Union (E) then
3270 elsif Checks_May_Be_Suppressed (E) then
3271 return Is_Check_Suppressed (E, Discriminant_Check);
3275 return Scope_Suppress (Discriminant_Check);
3276 end Discriminant_Checks_Suppressed;
3278 --------------------------------
3279 -- Division_Checks_Suppressed --
3280 --------------------------------
3282 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3284 if Present (E) and then Checks_May_Be_Suppressed (E) then
3285 return Is_Check_Suppressed (E, Division_Check);
3287 return Scope_Suppress (Division_Check);
3289 end Division_Checks_Suppressed;
3291 -----------------------------------
3292 -- Elaboration_Checks_Suppressed --
3293 -----------------------------------
3295 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3297 -- The complication in this routine is that if we are in the dynamic
3298 -- model of elaboration, we also check All_Checks, since All_Checks
3299 -- does not set Elaboration_Check explicitly.
3302 if Kill_Elaboration_Checks (E) then
3305 elsif Checks_May_Be_Suppressed (E) then
3306 if Is_Check_Suppressed (E, Elaboration_Check) then
3308 elsif Dynamic_Elaboration_Checks then
3309 return Is_Check_Suppressed (E, All_Checks);
3316 if Scope_Suppress (Elaboration_Check) then
3318 elsif Dynamic_Elaboration_Checks then
3319 return Scope_Suppress (All_Checks);
3323 end Elaboration_Checks_Suppressed;
3325 ---------------------------
3326 -- Enable_Overflow_Check --
3327 ---------------------------
3329 procedure Enable_Overflow_Check (N : Node_Id) is
3330 Typ : constant Entity_Id := Base_Type (Etype (N));
3339 if Debug_Flag_CC then
3340 w ("Enable_Overflow_Check for node ", Int (N));
3341 Write_Str (" Source location = ");
3346 -- Nothing to do if the range of the result is known OK. We skip this
3347 -- for conversions, since the caller already did the check, and in any
3348 -- case the condition for deleting the check for a type conversion is
3349 -- different in any case.
3351 if Nkind (N) /= N_Type_Conversion then
3352 Determine_Range (N, OK, Lo, Hi);
3354 -- Note in the test below that we assume that if a bound of the
3355 -- range is equal to that of the type. That's not quite accurate
3356 -- but we do this for the following reasons:
3358 -- a) The way that Determine_Range works, it will typically report
3359 -- the bounds of the value as being equal to the bounds of the
3360 -- type, because it either can't tell anything more precise, or
3361 -- does not think it is worth the effort to be more precise.
3363 -- b) It is very unusual to have a situation in which this would
3364 -- generate an unnecessary overflow check (an example would be
3365 -- a subtype with a range 0 .. Integer'Last - 1 to which the
3366 -- literal value one is added.
3368 -- c) The alternative is a lot of special casing in this routine
3369 -- which would partially duplicate Determine_Range processing.
3372 and then Lo > Expr_Value (Type_Low_Bound (Typ))
3373 and then Hi < Expr_Value (Type_High_Bound (Typ))
3375 if Debug_Flag_CC then
3376 w ("No overflow check required");
3383 -- If not in optimizing mode, set flag and we are done. We are also done
3384 -- (and just set the flag) if the type is not a discrete type, since it
3385 -- is not worth the effort to eliminate checks for other than discrete
3386 -- types. In addition, we take this same path if we have stored the
3387 -- maximum number of checks possible already (a very unlikely situation,
3388 -- but we do not want to blow up!)
3390 if Optimization_Level = 0
3391 or else not Is_Discrete_Type (Etype (N))
3392 or else Num_Saved_Checks = Saved_Checks'Last
3394 Activate_Overflow_Check (N);
3396 if Debug_Flag_CC then
3397 w ("Optimization off");
3403 -- Otherwise evaluate and check the expression
3408 Target_Type => Empty,
3414 if Debug_Flag_CC then
3415 w ("Called Find_Check");
3419 w (" Check_Num = ", Chk);
3420 w (" Ent = ", Int (Ent));
3421 Write_Str (" Ofs = ");
3426 -- If check is not of form to optimize, then set flag and we are done
3429 Activate_Overflow_Check (N);
3433 -- If check is already performed, then return without setting flag
3436 if Debug_Flag_CC then
3437 w ("Check suppressed!");
3443 -- Here we will make a new entry for the new check
3445 Activate_Overflow_Check (N);
3446 Num_Saved_Checks := Num_Saved_Checks + 1;
3447 Saved_Checks (Num_Saved_Checks) :=
3452 Target_Type => Empty);
3454 if Debug_Flag_CC then
3455 w ("Make new entry, check number = ", Num_Saved_Checks);
3456 w (" Entity = ", Int (Ent));
3457 Write_Str (" Offset = ");
3459 w (" Check_Type = O");
3460 w (" Target_Type = Empty");
3463 -- If we get an exception, then something went wrong, probably because of
3464 -- an error in the structure of the tree due to an incorrect program. Or it
3465 -- may be a bug in the optimization circuit. In either case the safest
3466 -- thing is simply to set the check flag unconditionally.
3470 Activate_Overflow_Check (N);
3472 if Debug_Flag_CC then
3473 w (" exception occurred, overflow flag set");
3477 end Enable_Overflow_Check;
3479 ------------------------
3480 -- Enable_Range_Check --
3481 ------------------------
3483 procedure Enable_Range_Check (N : Node_Id) is
3492 -- Return if unchecked type conversion with range check killed. In this
3493 -- case we never set the flag (that's what Kill_Range_Check is about!)
3495 if Nkind (N) = N_Unchecked_Type_Conversion
3496 and then Kill_Range_Check (N)
3501 -- Check for various cases where we should suppress the range check
3503 -- No check if range checks suppressed for type of node
3505 if Present (Etype (N))
3506 and then Range_Checks_Suppressed (Etype (N))
3510 -- No check if node is an entity name, and range checks are suppressed
3511 -- for this entity, or for the type of this entity.
3513 elsif Is_Entity_Name (N)
3514 and then (Range_Checks_Suppressed (Entity (N))
3515 or else Range_Checks_Suppressed (Etype (Entity (N))))
3519 -- No checks if index of array, and index checks are suppressed for
3520 -- the array object or the type of the array.
3522 elsif Nkind (Parent (N)) = N_Indexed_Component then
3524 Pref : constant Node_Id := Prefix (Parent (N));
3526 if Is_Entity_Name (Pref)
3527 and then Index_Checks_Suppressed (Entity (Pref))
3530 elsif Index_Checks_Suppressed (Etype (Pref)) then
3536 -- Debug trace output
3538 if Debug_Flag_CC then
3539 w ("Enable_Range_Check for node ", Int (N));
3540 Write_Str (" Source location = ");
3545 -- If not in optimizing mode, set flag and we are done. We are also done
3546 -- (and just set the flag) if the type is not a discrete type, since it
3547 -- is not worth the effort to eliminate checks for other than discrete
3548 -- types. In addition, we take this same path if we have stored the
3549 -- maximum number of checks possible already (a very unlikely situation,
3550 -- but we do not want to blow up!)
3552 if Optimization_Level = 0
3553 or else No (Etype (N))
3554 or else not Is_Discrete_Type (Etype (N))
3555 or else Num_Saved_Checks = Saved_Checks'Last
3557 Activate_Range_Check (N);
3559 if Debug_Flag_CC then
3560 w ("Optimization off");
3566 -- Otherwise find out the target type
3570 -- For assignment, use left side subtype
3572 if Nkind (P) = N_Assignment_Statement
3573 and then Expression (P) = N
3575 Ttyp := Etype (Name (P));
3577 -- For indexed component, use subscript subtype
3579 elsif Nkind (P) = N_Indexed_Component then
3586 Atyp := Etype (Prefix (P));
3588 if Is_Access_Type (Atyp) then
3589 Atyp := Designated_Type (Atyp);
3591 -- If the prefix is an access to an unconstrained array,
3592 -- perform check unconditionally: it depends on the bounds of
3593 -- an object and we cannot currently recognize whether the test
3594 -- may be redundant.
3596 if not Is_Constrained (Atyp) then
3597 Activate_Range_Check (N);
3601 -- Ditto if the prefix is an explicit dereference whose designated
3602 -- type is unconstrained.
3604 elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3605 and then not Is_Constrained (Atyp)
3607 Activate_Range_Check (N);
3611 Indx := First_Index (Atyp);
3612 Subs := First (Expressions (P));
3615 Ttyp := Etype (Indx);
3624 -- For now, ignore all other cases, they are not so interesting
3627 if Debug_Flag_CC then
3628 w (" target type not found, flag set");
3631 Activate_Range_Check (N);
3635 -- Evaluate and check the expression
3640 Target_Type => Ttyp,
3646 if Debug_Flag_CC then
3647 w ("Called Find_Check");
3648 w ("Target_Typ = ", Int (Ttyp));
3652 w (" Check_Num = ", Chk);
3653 w (" Ent = ", Int (Ent));
3654 Write_Str (" Ofs = ");
3659 -- If check is not of form to optimize, then set flag and we are done
3662 if Debug_Flag_CC then
3663 w (" expression not of optimizable type, flag set");
3666 Activate_Range_Check (N);
3670 -- If check is already performed, then return without setting flag
3673 if Debug_Flag_CC then
3674 w ("Check suppressed!");
3680 -- Here we will make a new entry for the new check
3682 Activate_Range_Check (N);
3683 Num_Saved_Checks := Num_Saved_Checks + 1;
3684 Saved_Checks (Num_Saved_Checks) :=
3689 Target_Type => Ttyp);
3691 if Debug_Flag_CC then
3692 w ("Make new entry, check number = ", Num_Saved_Checks);
3693 w (" Entity = ", Int (Ent));
3694 Write_Str (" Offset = ");
3696 w (" Check_Type = R");
3697 w (" Target_Type = ", Int (Ttyp));
3698 pg (Union_Id (Ttyp));
3701 -- If we get an exception, then something went wrong, probably because of
3702 -- an error in the structure of the tree due to an incorrect program. Or
3703 -- it may be a bug in the optimization circuit. In either case the safest
3704 -- thing is simply to set the check flag unconditionally.
3708 Activate_Range_Check (N);
3710 if Debug_Flag_CC then
3711 w (" exception occurred, range flag set");
3715 end Enable_Range_Check;
3721 procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3722 Typ : constant Entity_Id := Etype (Expr);
3725 -- Ignore call if we are not doing any validity checking
3727 if not Validity_Checks_On then
3730 -- Ignore call if range or validity checks suppressed on entity or type
3732 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3735 -- No check required if expression is from the expander, we assume the
3736 -- expander will generate whatever checks are needed. Note that this is
3737 -- not just an optimization, it avoids infinite recursions!
3739 -- Unchecked conversions must be checked, unless they are initialized
3740 -- scalar values, as in a component assignment in an init proc.
3742 -- In addition, we force a check if Force_Validity_Checks is set
3744 elsif not Comes_From_Source (Expr)
3745 and then not Force_Validity_Checks
3746 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
3747 or else Kill_Range_Check (Expr))
3751 -- No check required if expression is known to have valid value
3753 elsif Expr_Known_Valid (Expr) then
3756 -- Ignore case of enumeration with holes where the flag is set not to
3757 -- worry about holes, since no special validity check is needed
3759 elsif Is_Enumeration_Type (Typ)
3760 and then Has_Non_Standard_Rep (Typ)
3765 -- No check required on the left-hand side of an assignment
3767 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
3768 and then Expr = Name (Parent (Expr))
3772 -- No check on a univeral real constant. The context will eventually
3773 -- convert it to a machine number for some target type, or report an
3776 elsif Nkind (Expr) = N_Real_Literal
3777 and then Etype (Expr) = Universal_Real
3781 -- If the expression denotes a component of a packed boolean arrray,
3782 -- no possible check applies. We ignore the old ACATS chestnuts that
3783 -- involve Boolean range True..True.
3785 -- Note: validity checks are generated for expressions that yield a
3786 -- scalar type, when it is possible to create a value that is outside of
3787 -- the type. If this is a one-bit boolean no such value exists. This is
3788 -- an optimization, and it also prevents compiler blowing up during the
3789 -- elaboration of improperly expanded packed array references.
3791 elsif Nkind (Expr) = N_Indexed_Component
3792 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
3793 and then Root_Type (Etype (Expr)) = Standard_Boolean
3797 -- An annoying special case. If this is an out parameter of a scalar
3798 -- type, then the value is not going to be accessed, therefore it is
3799 -- inappropriate to do any validity check at the call site.
3802 -- Only need to worry about scalar types
3804 if Is_Scalar_Type (Typ) then
3814 -- Find actual argument (which may be a parameter association)
3815 -- and the parent of the actual argument (the call statement)
3820 if Nkind (P) = N_Parameter_Association then
3825 -- Only need to worry if we are argument of a procedure call
3826 -- since functions don't have out parameters. If this is an
3827 -- indirect or dispatching call, get signature from the
3830 if Nkind (P) = N_Procedure_Call_Statement then
3831 L := Parameter_Associations (P);
3833 if Is_Entity_Name (Name (P)) then
3834 E := Entity (Name (P));
3836 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
3837 E := Etype (Name (P));
3840 -- Only need to worry if there are indeed actuals, and if
3841 -- this could be a procedure call, otherwise we cannot get a
3842 -- match (either we are not an argument, or the mode of the
3843 -- formal is not OUT). This test also filters out the
3846 if Is_Non_Empty_List (L)
3847 and then Is_Subprogram (E)
3849 -- This is the loop through parameters, looking for an
3850 -- OUT parameter for which we are the argument.
3852 F := First_Formal (E);
3854 while Present (F) loop
3855 if Ekind (F) = E_Out_Parameter and then A = N then
3868 -- If we fall through, a validity check is required
3870 Insert_Valid_Check (Expr);
3873 ----------------------
3874 -- Expr_Known_Valid --
3875 ----------------------
3877 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
3878 Typ : constant Entity_Id := Etype (Expr);
3881 -- Non-scalar types are always considered valid, since they never give
3882 -- rise to the issues of erroneous or bounded error behavior that are
3883 -- the concern. In formal reference manual terms the notion of validity
3884 -- only applies to scalar types. Note that even when packed arrays are
3885 -- represented using modular types, they are still arrays semantically,
3886 -- so they are also always valid (in particular, the unused bits can be
3887 -- random rubbish without affecting the validity of the array value).
3889 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
3892 -- If no validity checking, then everything is considered valid
3894 elsif not Validity_Checks_On then
3897 -- Floating-point types are considered valid unless floating-point
3898 -- validity checks have been specifically turned on.
3900 elsif Is_Floating_Point_Type (Typ)
3901 and then not Validity_Check_Floating_Point
3905 -- If the expression is the value of an object that is known to be
3906 -- valid, then clearly the expression value itself is valid.
3908 elsif Is_Entity_Name (Expr)
3909 and then Is_Known_Valid (Entity (Expr))
3913 -- References to discriminants are always considered valid. The value
3914 -- of a discriminant gets checked when the object is built. Within the
3915 -- record, we consider it valid, and it is important to do so, since
3916 -- otherwise we can try to generate bogus validity checks which
3917 -- reference discriminants out of scope. Discriminants of concurrent
3918 -- types are excluded for the same reason.
3920 elsif Is_Entity_Name (Expr)
3921 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
3925 -- If the type is one for which all values are known valid, then we are
3926 -- sure that the value is valid except in the slightly odd case where
3927 -- the expression is a reference to a variable whose size has been
3928 -- explicitly set to a value greater than the object size.
3930 elsif Is_Known_Valid (Typ) then
3931 if Is_Entity_Name (Expr)
3932 and then Ekind (Entity (Expr)) = E_Variable
3933 and then Esize (Entity (Expr)) > Esize (Typ)
3940 -- Integer and character literals always have valid values, where
3941 -- appropriate these will be range checked in any case.
3943 elsif Nkind (Expr) = N_Integer_Literal
3945 Nkind (Expr) = N_Character_Literal
3949 -- If we have a type conversion or a qualification of a known valid
3950 -- value, then the result will always be valid.
3952 elsif Nkind (Expr) = N_Type_Conversion
3954 Nkind (Expr) = N_Qualified_Expression
3956 return Expr_Known_Valid (Expression (Expr));
3958 -- The result of any operator is always considered valid, since we
3959 -- assume the necessary checks are done by the operator. For operators
3960 -- on floating-point operations, we must also check when the operation
3961 -- is the right-hand side of an assignment, or is an actual in a call.
3963 elsif Nkind (Expr) in N_Op then
3964 if Is_Floating_Point_Type (Typ)
3965 and then Validity_Check_Floating_Point
3967 (Nkind (Parent (Expr)) = N_Assignment_Statement
3968 or else Nkind (Parent (Expr)) = N_Function_Call
3969 or else Nkind (Parent (Expr)) = N_Parameter_Association)
3976 -- The result of a membership test is always valid, since it is true or
3977 -- false, there are no other possibilities.
3979 elsif Nkind (Expr) in N_Membership_Test then
3982 -- For all other cases, we do not know the expression is valid
3987 end Expr_Known_Valid;
3993 procedure Find_Check
3995 Check_Type : Character;
3996 Target_Type : Entity_Id;
3997 Entry_OK : out Boolean;
3998 Check_Num : out Nat;
3999 Ent : out Entity_Id;
4002 function Within_Range_Of
4003 (Target_Type : Entity_Id;
4004 Check_Type : Entity_Id) return Boolean;
4005 -- Given a requirement for checking a range against Target_Type, and
4006 -- and a range Check_Type against which a check has already been made,
4007 -- determines if the check against check type is sufficient to ensure
4008 -- that no check against Target_Type is required.
4010 ---------------------
4011 -- Within_Range_Of --
4012 ---------------------
4014 function Within_Range_Of
4015 (Target_Type : Entity_Id;
4016 Check_Type : Entity_Id) return Boolean
4019 if Target_Type = Check_Type then
4024 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
4025 Thi : constant Node_Id := Type_High_Bound (Target_Type);
4026 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
4027 Chi : constant Node_Id := Type_High_Bound (Check_Type);
4031 or else (Compile_Time_Known_Value (Tlo)
4033 Compile_Time_Known_Value (Clo)
4035 Expr_Value (Clo) >= Expr_Value (Tlo)))
4038 or else (Compile_Time_Known_Value (Thi)
4040 Compile_Time_Known_Value (Chi)
4042 Expr_Value (Chi) <= Expr_Value (Clo)))
4050 end Within_Range_Of;
4052 -- Start of processing for Find_Check
4055 -- Establish default, to avoid warnings from GCC
4059 -- Case of expression is simple entity reference
4061 if Is_Entity_Name (Expr) then
4062 Ent := Entity (Expr);
4065 -- Case of expression is entity + known constant
4067 elsif Nkind (Expr) = N_Op_Add
4068 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4069 and then Is_Entity_Name (Left_Opnd (Expr))
4071 Ent := Entity (Left_Opnd (Expr));
4072 Ofs := Expr_Value (Right_Opnd (Expr));
4074 -- Case of expression is entity - known constant
4076 elsif Nkind (Expr) = N_Op_Subtract
4077 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4078 and then Is_Entity_Name (Left_Opnd (Expr))
4080 Ent := Entity (Left_Opnd (Expr));
4081 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4083 -- Any other expression is not of the right form
4092 -- Come here with expression of appropriate form, check if entity is an
4093 -- appropriate one for our purposes.
4095 if (Ekind (Ent) = E_Variable
4097 Ekind (Ent) = E_Constant
4099 Ekind (Ent) = E_Loop_Parameter
4101 Ekind (Ent) = E_In_Parameter)
4102 and then not Is_Library_Level_Entity (Ent)
4110 -- See if there is matching check already
4112 for J in reverse 1 .. Num_Saved_Checks loop
4114 SC : Saved_Check renames Saved_Checks (J);
4117 if SC.Killed = False
4118 and then SC.Entity = Ent
4119 and then SC.Offset = Ofs
4120 and then SC.Check_Type = Check_Type
4121 and then Within_Range_Of (Target_Type, SC.Target_Type)
4129 -- If we fall through entry was not found
4135 ---------------------------------
4136 -- Generate_Discriminant_Check --
4137 ---------------------------------
4139 -- Note: the code for this procedure is derived from the
4140 -- Emit_Discriminant_Check Routine in trans.c.
4142 procedure Generate_Discriminant_Check (N : Node_Id) is
4143 Loc : constant Source_Ptr := Sloc (N);
4144 Pref : constant Node_Id := Prefix (N);
4145 Sel : constant Node_Id := Selector_Name (N);
4147 Orig_Comp : constant Entity_Id :=
4148 Original_Record_Component (Entity (Sel));
4149 -- The original component to be checked
4151 Discr_Fct : constant Entity_Id :=
4152 Discriminant_Checking_Func (Orig_Comp);
4153 -- The discriminant checking function
4156 -- One discriminant to be checked in the type
4158 Real_Discr : Entity_Id;
4159 -- Actual discriminant in the call
4161 Pref_Type : Entity_Id;
4162 -- Type of relevant prefix (ignoring private/access stuff)
4165 -- List of arguments for function call
4168 -- Keep track of the formal corresponding to the actual we build for
4169 -- each discriminant, in order to be able to perform the necessary type
4173 -- Selected component reference for checking function argument
4176 Pref_Type := Etype (Pref);
4178 -- Force evaluation of the prefix, so that it does not get evaluated
4179 -- twice (once for the check, once for the actual reference). Such a
4180 -- double evaluation is always a potential source of inefficiency,
4181 -- and is functionally incorrect in the volatile case, or when the
4182 -- prefix may have side-effects. An entity or a component of an
4183 -- entity requires no evaluation.
4185 if Is_Entity_Name (Pref) then
4186 if Treat_As_Volatile (Entity (Pref)) then
4187 Force_Evaluation (Pref, Name_Req => True);
4190 elsif Treat_As_Volatile (Etype (Pref)) then
4191 Force_Evaluation (Pref, Name_Req => True);
4193 elsif Nkind (Pref) = N_Selected_Component
4194 and then Is_Entity_Name (Prefix (Pref))
4199 Force_Evaluation (Pref, Name_Req => True);
4202 -- For a tagged type, use the scope of the original component to
4203 -- obtain the type, because ???
4205 if Is_Tagged_Type (Scope (Orig_Comp)) then
4206 Pref_Type := Scope (Orig_Comp);
4208 -- For an untagged derived type, use the discriminants of the parent
4209 -- which have been renamed in the derivation, possibly by a one-to-many
4210 -- discriminant constraint. For non-tagged type, initially get the Etype
4214 if Is_Derived_Type (Pref_Type)
4215 and then Number_Discriminants (Pref_Type) /=
4216 Number_Discriminants (Etype (Base_Type (Pref_Type)))
4218 Pref_Type := Etype (Base_Type (Pref_Type));
4222 -- We definitely should have a checking function, This routine should
4223 -- not be called if no discriminant checking function is present.
4225 pragma Assert (Present (Discr_Fct));
4227 -- Create the list of the actual parameters for the call. This list
4228 -- is the list of the discriminant fields of the record expression to
4229 -- be discriminant checked.
4232 Formal := First_Formal (Discr_Fct);
4233 Discr := First_Discriminant (Pref_Type);
4234 while Present (Discr) loop
4236 -- If we have a corresponding discriminant field, and a parent
4237 -- subtype is present, then we want to use the corresponding
4238 -- discriminant since this is the one with the useful value.
4240 if Present (Corresponding_Discriminant (Discr))
4241 and then Ekind (Pref_Type) = E_Record_Type
4242 and then Present (Parent_Subtype (Pref_Type))
4244 Real_Discr := Corresponding_Discriminant (Discr);
4246 Real_Discr := Discr;
4249 -- Construct the reference to the discriminant
4252 Make_Selected_Component (Loc,
4254 Unchecked_Convert_To (Pref_Type,
4255 Duplicate_Subexpr (Pref)),
4256 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4258 -- Manually analyze and resolve this selected component. We really
4259 -- want it just as it appears above, and do not want the expander
4260 -- playing discriminal games etc with this reference. Then we append
4261 -- the argument to the list we are gathering.
4263 Set_Etype (Scomp, Etype (Real_Discr));
4264 Set_Analyzed (Scomp, True);
4265 Append_To (Args, Convert_To (Etype (Formal), Scomp));
4267 Next_Formal_With_Extras (Formal);
4268 Next_Discriminant (Discr);
4271 -- Now build and insert the call
4274 Make_Raise_Constraint_Error (Loc,
4276 Make_Function_Call (Loc,
4277 Name => New_Occurrence_Of (Discr_Fct, Loc),
4278 Parameter_Associations => Args),
4279 Reason => CE_Discriminant_Check_Failed));
4280 end Generate_Discriminant_Check;
4282 ---------------------------
4283 -- Generate_Index_Checks --
4284 ---------------------------
4286 procedure Generate_Index_Checks (N : Node_Id) is
4287 Loc : constant Source_Ptr := Sloc (N);
4288 A : constant Node_Id := Prefix (N);
4294 -- Ignore call if index checks suppressed for array object or type
4296 if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4297 or else Index_Checks_Suppressed (Etype (A))
4302 -- Generate the checks
4304 Sub := First (Expressions (N));
4306 while Present (Sub) loop
4307 if Do_Range_Check (Sub) then
4308 Set_Do_Range_Check (Sub, False);
4310 -- Force evaluation except for the case of a simple name of a
4311 -- non-volatile entity.
4313 if not Is_Entity_Name (Sub)
4314 or else Treat_As_Volatile (Entity (Sub))
4316 Force_Evaluation (Sub);
4319 -- Generate a raise of constraint error with the appropriate
4320 -- reason and a condition of the form:
4322 -- Base_Type(Sub) not in array'range (subscript)
4324 -- Note that the reason we generate the conversion to the base
4325 -- type here is that we definitely want the range check to take
4326 -- place, even if it looks like the subtype is OK. Optimization
4327 -- considerations that allow us to omit the check have already
4328 -- been taken into account in the setting of the Do_Range_Check
4334 Num := New_List (Make_Integer_Literal (Loc, Ind));
4338 Make_Raise_Constraint_Error (Loc,
4342 Convert_To (Base_Type (Etype (Sub)),
4343 Duplicate_Subexpr_Move_Checks (Sub)),
4345 Make_Attribute_Reference (Loc,
4346 Prefix => Duplicate_Subexpr_Move_Checks (A),
4347 Attribute_Name => Name_Range,
4348 Expressions => Num)),
4349 Reason => CE_Index_Check_Failed));
4355 end Generate_Index_Checks;
4357 --------------------------
4358 -- Generate_Range_Check --
4359 --------------------------
4361 procedure Generate_Range_Check
4363 Target_Type : Entity_Id;
4364 Reason : RT_Exception_Code)
4366 Loc : constant Source_Ptr := Sloc (N);
4367 Source_Type : constant Entity_Id := Etype (N);
4368 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
4369 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
4372 -- First special case, if the source type is already within the range
4373 -- of the target type, then no check is needed (probably we should have
4374 -- stopped Do_Range_Check from being set in the first place, but better
4375 -- late than later in preventing junk code!
4377 -- We do NOT apply this if the source node is a literal, since in this
4378 -- case the literal has already been labeled as having the subtype of
4381 if In_Subrange_Of (Source_Type, Target_Type)
4383 (Nkind (N) = N_Integer_Literal
4385 Nkind (N) = N_Real_Literal
4387 Nkind (N) = N_Character_Literal
4390 and then Ekind (Entity (N)) = E_Enumeration_Literal))
4395 -- We need a check, so force evaluation of the node, so that it does
4396 -- not get evaluated twice (once for the check, once for the actual
4397 -- reference). Such a double evaluation is always a potential source
4398 -- of inefficiency, and is functionally incorrect in the volatile case.
4400 if not Is_Entity_Name (N)
4401 or else Treat_As_Volatile (Entity (N))
4403 Force_Evaluation (N);
4406 -- The easiest case is when Source_Base_Type and Target_Base_Type are
4407 -- the same since in this case we can simply do a direct check of the
4408 -- value of N against the bounds of Target_Type.
4410 -- [constraint_error when N not in Target_Type]
4412 -- Note: this is by far the most common case, for example all cases of
4413 -- checks on the RHS of assignments are in this category, but not all
4414 -- cases are like this. Notably conversions can involve two types.
4416 if Source_Base_Type = Target_Base_Type then
4418 Make_Raise_Constraint_Error (Loc,
4421 Left_Opnd => Duplicate_Subexpr (N),
4422 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4425 -- Next test for the case where the target type is within the bounds
4426 -- of the base type of the source type, since in this case we can
4427 -- simply convert these bounds to the base type of T to do the test.
4429 -- [constraint_error when N not in
4430 -- Source_Base_Type (Target_Type'First)
4432 -- Source_Base_Type(Target_Type'Last))]
4434 -- The conversions will always work and need no check
4436 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4438 Make_Raise_Constraint_Error (Loc,
4441 Left_Opnd => Duplicate_Subexpr (N),
4446 Convert_To (Source_Base_Type,
4447 Make_Attribute_Reference (Loc,
4449 New_Occurrence_Of (Target_Type, Loc),
4450 Attribute_Name => Name_First)),
4453 Convert_To (Source_Base_Type,
4454 Make_Attribute_Reference (Loc,
4456 New_Occurrence_Of (Target_Type, Loc),
4457 Attribute_Name => Name_Last)))),
4460 -- Note that at this stage we now that the Target_Base_Type is not in
4461 -- the range of the Source_Base_Type (since even the Target_Type itself
4462 -- is not in this range). It could still be the case that Source_Type is
4463 -- in range of the target base type since we have not checked that case.
4465 -- If that is the case, we can freely convert the source to the target,
4466 -- and then test the target result against the bounds.
4468 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4470 -- We make a temporary to hold the value of the converted value
4471 -- (converted to the base type), and then we will do the test against
4474 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
4475 -- [constraint_error when Tnn not in Target_Type]
4477 -- Then the conversion itself is replaced by an occurrence of Tnn
4480 Tnn : constant Entity_Id :=
4481 Make_Defining_Identifier (Loc,
4482 Chars => New_Internal_Name ('T'));
4485 Insert_Actions (N, New_List (
4486 Make_Object_Declaration (Loc,
4487 Defining_Identifier => Tnn,
4488 Object_Definition =>
4489 New_Occurrence_Of (Target_Base_Type, Loc),
4490 Constant_Present => True,
4492 Make_Type_Conversion (Loc,
4493 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4494 Expression => Duplicate_Subexpr (N))),
4496 Make_Raise_Constraint_Error (Loc,
4499 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4500 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4502 Reason => Reason)));
4504 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4506 -- Set the type of N, because the declaration for Tnn might not
4507 -- be analyzed yet, as is the case if N appears within a record
4508 -- declaration, as a discriminant constraint or expression.
4510 Set_Etype (N, Target_Base_Type);
4513 -- At this stage, we know that we have two scalar types, which are
4514 -- directly convertible, and where neither scalar type has a base
4515 -- range that is in the range of the other scalar type.
4517 -- The only way this can happen is with a signed and unsigned type.
4518 -- So test for these two cases:
4521 -- Case of the source is unsigned and the target is signed
4523 if Is_Unsigned_Type (Source_Base_Type)
4524 and then not Is_Unsigned_Type (Target_Base_Type)
4526 -- If the source is unsigned and the target is signed, then we
4527 -- know that the source is not shorter than the target (otherwise
4528 -- the source base type would be in the target base type range).
4530 -- In other words, the unsigned type is either the same size as
4531 -- the target, or it is larger. It cannot be smaller.
4534 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4536 -- We only need to check the low bound if the low bound of the
4537 -- target type is non-negative. If the low bound of the target
4538 -- type is negative, then we know that we will fit fine.
4540 -- If the high bound of the target type is negative, then we
4541 -- know we have a constraint error, since we can't possibly
4542 -- have a negative source.
4544 -- With these two checks out of the way, we can do the check
4545 -- using the source type safely
4547 -- This is definitely the most annoying case!
4549 -- [constraint_error
4550 -- when (Target_Type'First >= 0
4552 -- N < Source_Base_Type (Target_Type'First))
4553 -- or else Target_Type'Last < 0
4554 -- or else N > Source_Base_Type (Target_Type'Last)];
4556 -- We turn off all checks since we know that the conversions
4557 -- will work fine, given the guards for negative values.
4560 Make_Raise_Constraint_Error (Loc,
4566 Left_Opnd => Make_Op_Ge (Loc,
4568 Make_Attribute_Reference (Loc,
4570 New_Occurrence_Of (Target_Type, Loc),
4571 Attribute_Name => Name_First),
4572 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4576 Left_Opnd => Duplicate_Subexpr (N),
4578 Convert_To (Source_Base_Type,
4579 Make_Attribute_Reference (Loc,
4581 New_Occurrence_Of (Target_Type, Loc),
4582 Attribute_Name => Name_First)))),
4587 Make_Attribute_Reference (Loc,
4588 Prefix => New_Occurrence_Of (Target_Type, Loc),
4589 Attribute_Name => Name_Last),
4590 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4594 Left_Opnd => Duplicate_Subexpr (N),
4596 Convert_To (Source_Base_Type,
4597 Make_Attribute_Reference (Loc,
4598 Prefix => New_Occurrence_Of (Target_Type, Loc),
4599 Attribute_Name => Name_Last)))),
4602 Suppress => All_Checks);
4604 -- Only remaining possibility is that the source is signed and
4605 -- the target is unsigned
4608 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4609 and then Is_Unsigned_Type (Target_Base_Type));
4611 -- If the source is signed and the target is unsigned, then we
4612 -- know that the target is not shorter than the source (otherwise
4613 -- the target base type would be in the source base type range).
4615 -- In other words, the unsigned type is either the same size as
4616 -- the target, or it is larger. It cannot be smaller.
4618 -- Clearly we have an error if the source value is negative since
4619 -- no unsigned type can have negative values. If the source type
4620 -- is non-negative, then the check can be done using the target
4623 -- Tnn : constant Target_Base_Type (N) := Target_Type;
4625 -- [constraint_error
4626 -- when N < 0 or else Tnn not in Target_Type];
4628 -- We turn off all checks for the conversion of N to the target
4629 -- base type, since we generate the explicit check to ensure that
4630 -- the value is non-negative
4633 Tnn : constant Entity_Id :=
4634 Make_Defining_Identifier (Loc,
4635 Chars => New_Internal_Name ('T'));
4638 Insert_Actions (N, New_List (
4639 Make_Object_Declaration (Loc,
4640 Defining_Identifier => Tnn,
4641 Object_Definition =>
4642 New_Occurrence_Of (Target_Base_Type, Loc),
4643 Constant_Present => True,
4645 Make_Type_Conversion (Loc,
4647 New_Occurrence_Of (Target_Base_Type, Loc),
4648 Expression => Duplicate_Subexpr (N))),
4650 Make_Raise_Constraint_Error (Loc,
4655 Left_Opnd => Duplicate_Subexpr (N),
4656 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4660 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4662 New_Occurrence_Of (Target_Type, Loc))),
4665 Suppress => All_Checks);
4667 -- Set the Etype explicitly, because Insert_Actions may have
4668 -- placed the declaration in the freeze list for an enclosing
4669 -- construct, and thus it is not analyzed yet.
4671 Set_Etype (Tnn, Target_Base_Type);
4672 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4676 end Generate_Range_Check;
4682 function Get_Check_Id (N : Name_Id) return Check_Id is
4684 -- For standard check name, we can do a direct computation
4686 if N in First_Check_Name .. Last_Check_Name then
4687 return Check_Id (N - (First_Check_Name - 1));
4689 -- For non-standard names added by pragma Check_Name, search table
4692 for J in All_Checks + 1 .. Check_Names.Last loop
4693 if Check_Names.Table (J) = N then
4699 -- No matching name found
4704 ---------------------
4705 -- Get_Discriminal --
4706 ---------------------
4708 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4709 Loc : constant Source_Ptr := Sloc (E);
4714 -- The bound can be a bona fide parameter of a protected operation,
4715 -- rather than a prival encoded as an in-parameter.
4717 if No (Discriminal_Link (Entity (Bound))) then
4721 -- Climb the scope stack looking for an enclosing protected type. If
4722 -- we run out of scopes, return the bound itself.
4725 while Present (Sc) loop
4726 if Sc = Standard_Standard then
4729 elsif Ekind (Sc) = E_Protected_Type then
4736 D := First_Discriminant (Sc);
4737 while Present (D) loop
4738 if Chars (D) = Chars (Bound) then
4739 return New_Occurrence_Of (Discriminal (D), Loc);
4742 Next_Discriminant (D);
4746 end Get_Discriminal;
4748 ----------------------
4749 -- Get_Range_Checks --
4750 ----------------------
4752 function Get_Range_Checks
4754 Target_Typ : Entity_Id;
4755 Source_Typ : Entity_Id := Empty;
4756 Warn_Node : Node_Id := Empty) return Check_Result
4759 return Selected_Range_Checks
4760 (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
4761 end Get_Range_Checks;
4767 function Guard_Access
4770 Ck_Node : Node_Id) return Node_Id
4773 if Nkind (Cond) = N_Or_Else then
4774 Set_Paren_Count (Cond, 1);
4777 if Nkind (Ck_Node) = N_Allocator then
4784 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
4785 Right_Opnd => Make_Null (Loc)),
4786 Right_Opnd => Cond);
4790 -----------------------------
4791 -- Index_Checks_Suppressed --
4792 -----------------------------
4794 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
4796 if Present (E) and then Checks_May_Be_Suppressed (E) then
4797 return Is_Check_Suppressed (E, Index_Check);
4799 return Scope_Suppress (Index_Check);
4801 end Index_Checks_Suppressed;
4807 procedure Initialize is
4809 for J in Determine_Range_Cache_N'Range loop
4810 Determine_Range_Cache_N (J) := Empty;
4815 for J in Int range 1 .. All_Checks loop
4816 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
4820 -------------------------
4821 -- Insert_Range_Checks --
4822 -------------------------
4824 procedure Insert_Range_Checks
4825 (Checks : Check_Result;
4827 Suppress_Typ : Entity_Id;
4828 Static_Sloc : Source_Ptr := No_Location;
4829 Flag_Node : Node_Id := Empty;
4830 Do_Before : Boolean := False)
4832 Internal_Flag_Node : Node_Id := Flag_Node;
4833 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
4835 Check_Node : Node_Id;
4836 Checks_On : constant Boolean :=
4837 (not Index_Checks_Suppressed (Suppress_Typ))
4839 (not Range_Checks_Suppressed (Suppress_Typ));
4842 -- For now we just return if Checks_On is false, however this should be
4843 -- enhanced to check for an always True value in the condition and to
4844 -- generate a compilation warning???
4846 if not Expander_Active or else not Checks_On then
4850 if Static_Sloc = No_Location then
4851 Internal_Static_Sloc := Sloc (Node);
4854 if No (Flag_Node) then
4855 Internal_Flag_Node := Node;
4858 for J in 1 .. 2 loop
4859 exit when No (Checks (J));
4861 if Nkind (Checks (J)) = N_Raise_Constraint_Error
4862 and then Present (Condition (Checks (J)))
4864 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
4865 Check_Node := Checks (J);
4866 Mark_Rewrite_Insertion (Check_Node);
4869 Insert_Before_And_Analyze (Node, Check_Node);
4871 Insert_After_And_Analyze (Node, Check_Node);
4874 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
4879 Make_Raise_Constraint_Error (Internal_Static_Sloc,
4880 Reason => CE_Range_Check_Failed);
4881 Mark_Rewrite_Insertion (Check_Node);
4884 Insert_Before_And_Analyze (Node, Check_Node);
4886 Insert_After_And_Analyze (Node, Check_Node);
4890 end Insert_Range_Checks;
4892 ------------------------
4893 -- Insert_Valid_Check --
4894 ------------------------
4896 procedure Insert_Valid_Check (Expr : Node_Id) is
4897 Loc : constant Source_Ptr := Sloc (Expr);
4901 -- Do not insert if checks off, or if not checking validity
4903 if not Validity_Checks_On
4904 or else Range_Or_Validity_Checks_Suppressed (Expr)
4909 -- If we have a checked conversion, then validity check applies to
4910 -- the expression inside the conversion, not the result, since if
4911 -- the expression inside is valid, then so is the conversion result.
4914 while Nkind (Exp) = N_Type_Conversion loop
4915 Exp := Expression (Exp);
4918 -- We are about to insert the validity check for Exp. We save and
4919 -- reset the Do_Range_Check flag over this validity check, and then
4920 -- put it back for the final original reference (Exp may be rewritten).
4923 DRC : constant Boolean := Do_Range_Check (Exp);
4926 Set_Do_Range_Check (Exp, False);
4928 -- Insert the validity check. Note that we do this with validity
4929 -- checks turned off, to avoid recursion, we do not want validity
4930 -- checks on the validity checking code itself!
4934 Make_Raise_Constraint_Error (Loc,
4938 Make_Attribute_Reference (Loc,
4940 Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
4941 Attribute_Name => Name_Valid)),
4942 Reason => CE_Invalid_Data),
4943 Suppress => Validity_Check);
4945 -- If the expression is a a reference to an element of a bit-packed
4946 -- array, then it is rewritten as a renaming declaration. If the
4947 -- expression is an actual in a call, it has not been expanded,
4948 -- waiting for the proper point at which to do it. The same happens
4949 -- with renamings, so that we have to force the expansion now. This
4950 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
4953 if Is_Entity_Name (Exp)
4954 and then Nkind (Parent (Entity (Exp))) =
4955 N_Object_Renaming_Declaration
4958 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
4960 if Nkind (Old_Exp) = N_Indexed_Component
4961 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
4963 Expand_Packed_Element_Reference (Old_Exp);
4968 -- Put back the Do_Range_Check flag on the resulting (possibly
4969 -- rewritten) expression.
4971 -- Note: it might be thought that a validity check is not required
4972 -- when a range check is present, but that's not the case, because
4973 -- the back end is allowed to assume for the range check that the
4974 -- operand is within its declared range (an assumption that validity
4975 -- checking is all about NOT assuming!)
4977 -- Note: no need to worry about Possible_Local_Raise here, it will
4978 -- already have been called if original node has Do_Range_Check set.
4980 Set_Do_Range_Check (Exp, DRC);
4982 end Insert_Valid_Check;
4984 ----------------------------------
4985 -- Install_Null_Excluding_Check --
4986 ----------------------------------
4988 procedure Install_Null_Excluding_Check (N : Node_Id) is
4989 Loc : constant Source_Ptr := Sloc (N);
4990 Typ : constant Entity_Id := Etype (N);
4992 function In_Declarative_Region_Of_Subprogram_Body return Boolean;
4993 -- Determine whether node N, a reference to an *in* parameter, is
4994 -- inside the declarative region of the current subprogram body.
4996 procedure Mark_Non_Null;
4997 -- After installation of check, if the node in question is an entity
4998 -- name, then mark this entity as non-null if possible.
5000 ----------------------------------------------
5001 -- In_Declarative_Region_Of_Subprogram_Body --
5002 ----------------------------------------------
5004 function In_Declarative_Region_Of_Subprogram_Body return Boolean is
5005 E : constant Entity_Id := Entity (N);
5006 S : constant Entity_Id := Current_Scope;
5010 pragma Assert (Ekind (E) = E_In_Parameter);
5012 -- Two initial context checks. We must be inside a subprogram body
5013 -- with declarations and reference must not appear in nested scopes.
5015 if (Ekind (S) /= E_Function
5016 and then Ekind (S) /= E_Procedure)
5017 or else Scope (E) /= S
5022 S_Par := Parent (Parent (S));
5024 if Nkind (S_Par) /= N_Subprogram_Body
5025 or else No (Declarations (S_Par))
5035 -- Retrieve the declaration node of N (if any). Note that N
5036 -- may be a part of a complex initialization expression.
5040 while Present (P) loop
5042 -- While traversing the parent chain, we find that N
5043 -- belongs to a statement, thus it may never appear in
5044 -- a declarative region.
5046 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5047 or else Nkind (P) = N_Procedure_Call_Statement
5052 if Nkind (P) in N_Declaration
5053 and then Nkind (P) not in N_Subprogram_Specification
5066 return List_Containing (N_Decl) = Declarations (S_Par);
5068 end In_Declarative_Region_Of_Subprogram_Body;
5074 procedure Mark_Non_Null is
5076 -- Only case of interest is if node N is an entity name
5078 if Is_Entity_Name (N) then
5080 -- For sure, we want to clear an indication that this is known to
5081 -- be null, since if we get past this check, it definitely is not!
5083 Set_Is_Known_Null (Entity (N), False);
5085 -- We can mark the entity as known to be non-null if either it is
5086 -- safe to capture the value, or in the case of an IN parameter,
5087 -- which is a constant, if the check we just installed is in the
5088 -- declarative region of the subprogram body. In this latter case,
5089 -- a check is decisive for the rest of the body, since we know we
5090 -- must complete all declarations before executing the body.
5092 if Safe_To_Capture_Value (N, Entity (N))
5094 (Ekind (Entity (N)) = E_In_Parameter
5095 and then In_Declarative_Region_Of_Subprogram_Body)
5097 Set_Is_Known_Non_Null (Entity (N));
5102 -- Start of processing for Install_Null_Excluding_Check
5105 pragma Assert (Is_Access_Type (Typ));
5107 -- No check inside a generic (why not???)
5109 if Inside_A_Generic then
5113 -- No check needed if known to be non-null
5115 if Known_Non_Null (N) then
5119 -- If known to be null, here is where we generate a compile time check
5121 if Known_Null (N) then
5122 Apply_Compile_Time_Constraint_Error
5124 "null value not allowed here?",
5125 CE_Access_Check_Failed);
5130 -- If entity is never assigned, for sure a warning is appropriate
5132 if Is_Entity_Name (N) then
5133 Check_Unset_Reference (N);
5136 -- No check needed if checks are suppressed on the range. Note that we
5137 -- don't set Is_Known_Non_Null in this case (we could legitimately do
5138 -- so, since the program is erroneous, but we don't like to casually
5139 -- propagate such conclusions from erroneosity).
5141 if Access_Checks_Suppressed (Typ) then
5145 -- No check needed for access to concurrent record types generated by
5146 -- the expander. This is not just an optimization (though it does indeed
5147 -- remove junk checks). It also avoids generation of junk warnings.
5149 if Nkind (N) in N_Has_Chars
5150 and then Chars (N) = Name_uObject
5151 and then Is_Concurrent_Record_Type
5152 (Directly_Designated_Type (Etype (N)))
5157 -- Otherwise install access check
5160 Make_Raise_Constraint_Error (Loc,
5163 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
5164 Right_Opnd => Make_Null (Loc)),
5165 Reason => CE_Access_Check_Failed));
5168 end Install_Null_Excluding_Check;
5170 --------------------------
5171 -- Install_Static_Check --
5172 --------------------------
5174 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5175 Stat : constant Boolean := Is_Static_Expression (R_Cno);
5176 Typ : constant Entity_Id := Etype (R_Cno);
5180 Make_Raise_Constraint_Error (Loc,
5181 Reason => CE_Range_Check_Failed));
5182 Set_Analyzed (R_Cno);
5183 Set_Etype (R_Cno, Typ);
5184 Set_Raises_Constraint_Error (R_Cno);
5185 Set_Is_Static_Expression (R_Cno, Stat);
5186 end Install_Static_Check;
5188 ---------------------
5189 -- Kill_All_Checks --
5190 ---------------------
5192 procedure Kill_All_Checks is
5194 if Debug_Flag_CC then
5195 w ("Kill_All_Checks");
5198 -- We reset the number of saved checks to zero, and also modify all
5199 -- stack entries for statement ranges to indicate that the number of
5200 -- checks at each level is now zero.
5202 Num_Saved_Checks := 0;
5204 for J in 1 .. Saved_Checks_TOS loop
5205 Saved_Checks_Stack (J) := 0;
5207 end Kill_All_Checks;
5213 procedure Kill_Checks (V : Entity_Id) is
5215 if Debug_Flag_CC then
5216 w ("Kill_Checks for entity", Int (V));
5219 for J in 1 .. Num_Saved_Checks loop
5220 if Saved_Checks (J).Entity = V then
5221 if Debug_Flag_CC then
5222 w (" Checks killed for saved check ", J);
5225 Saved_Checks (J).Killed := True;
5230 ------------------------------
5231 -- Length_Checks_Suppressed --
5232 ------------------------------
5234 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5236 if Present (E) and then Checks_May_Be_Suppressed (E) then
5237 return Is_Check_Suppressed (E, Length_Check);
5239 return Scope_Suppress (Length_Check);
5241 end Length_Checks_Suppressed;
5243 --------------------------------
5244 -- Overflow_Checks_Suppressed --
5245 --------------------------------
5247 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5249 if Present (E) and then Checks_May_Be_Suppressed (E) then
5250 return Is_Check_Suppressed (E, Overflow_Check);
5252 return Scope_Suppress (Overflow_Check);
5254 end Overflow_Checks_Suppressed;
5255 -----------------------------
5256 -- Range_Checks_Suppressed --
5257 -----------------------------
5259 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5263 -- Note: for now we always suppress range checks on Vax float types,
5264 -- since Gigi does not know how to generate these checks.
5266 if Vax_Float (E) then
5268 elsif Kill_Range_Checks (E) then
5270 elsif Checks_May_Be_Suppressed (E) then
5271 return Is_Check_Suppressed (E, Range_Check);
5275 return Scope_Suppress (Range_Check);
5276 end Range_Checks_Suppressed;
5278 -----------------------------------------
5279 -- Range_Or_Validity_Checks_Suppressed --
5280 -----------------------------------------
5282 -- Note: the coding would be simpler here if we simply made appropriate
5283 -- calls to Range/Validity_Checks_Suppressed, but that would result in
5284 -- duplicated checks which we prefer to avoid.
5286 function Range_Or_Validity_Checks_Suppressed
5287 (Expr : Node_Id) return Boolean
5290 -- Immediate return if scope checks suppressed for either check
5292 if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5296 -- If no expression, that's odd, decide that checks are suppressed,
5297 -- since we don't want anyone trying to do checks in this case, which
5298 -- is most likely the result of some other error.
5304 -- Expression is present, so perform suppress checks on type
5307 Typ : constant Entity_Id := Etype (Expr);
5309 if Vax_Float (Typ) then
5311 elsif Checks_May_Be_Suppressed (Typ)
5312 and then (Is_Check_Suppressed (Typ, Range_Check)
5314 Is_Check_Suppressed (Typ, Validity_Check))
5320 -- If expression is an entity name, perform checks on this entity
5322 if Is_Entity_Name (Expr) then
5324 Ent : constant Entity_Id := Entity (Expr);
5326 if Checks_May_Be_Suppressed (Ent) then
5327 return Is_Check_Suppressed (Ent, Range_Check)
5328 or else Is_Check_Suppressed (Ent, Validity_Check);
5333 -- If we fall through, no checks suppressed
5336 end Range_Or_Validity_Checks_Suppressed;
5342 procedure Remove_Checks (Expr : Node_Id) is
5343 Discard : Traverse_Result;
5344 pragma Warnings (Off, Discard);
5346 function Process (N : Node_Id) return Traverse_Result;
5347 -- Process a single node during the traversal
5349 function Traverse is new Traverse_Func (Process);
5350 -- The traversal function itself
5356 function Process (N : Node_Id) return Traverse_Result is
5358 if Nkind (N) not in N_Subexpr then
5362 Set_Do_Range_Check (N, False);
5366 Discard := Traverse (Left_Opnd (N));
5369 when N_Attribute_Reference =>
5370 Set_Do_Overflow_Check (N, False);
5372 when N_Function_Call =>
5373 Set_Do_Tag_Check (N, False);
5376 Set_Do_Overflow_Check (N, False);
5380 Set_Do_Division_Check (N, False);
5383 Set_Do_Length_Check (N, False);
5386 Set_Do_Division_Check (N, False);
5389 Set_Do_Length_Check (N, False);
5392 Set_Do_Division_Check (N, False);
5395 Set_Do_Length_Check (N, False);
5402 Discard := Traverse (Left_Opnd (N));
5405 when N_Selected_Component =>
5406 Set_Do_Discriminant_Check (N, False);
5408 when N_Type_Conversion =>
5409 Set_Do_Length_Check (N, False);
5410 Set_Do_Tag_Check (N, False);
5411 Set_Do_Overflow_Check (N, False);
5420 -- Start of processing for Remove_Checks
5423 Discard := Traverse (Expr);
5426 ----------------------------
5427 -- Selected_Length_Checks --
5428 ----------------------------
5430 function Selected_Length_Checks
5432 Target_Typ : Entity_Id;
5433 Source_Typ : Entity_Id;
5434 Warn_Node : Node_Id) return Check_Result
5436 Loc : constant Source_Ptr := Sloc (Ck_Node);
5439 Expr_Actual : Node_Id;
5441 Cond : Node_Id := Empty;
5442 Do_Access : Boolean := False;
5443 Wnode : Node_Id := Warn_Node;
5444 Ret_Result : Check_Result := (Empty, Empty);
5445 Num_Checks : Natural := 0;
5447 procedure Add_Check (N : Node_Id);
5448 -- Adds the action given to Ret_Result if N is non-Empty
5450 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5451 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5452 -- Comments required ???
5454 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5455 -- True for equal literals and for nodes that denote the same constant
5456 -- entity, even if its value is not a static constant. This includes the
5457 -- case of a discriminal reference within an init proc. Removes some
5458 -- obviously superfluous checks.
5460 function Length_E_Cond
5461 (Exptyp : Entity_Id;
5463 Indx : Nat) return Node_Id;
5464 -- Returns expression to compute:
5465 -- Typ'Length /= Exptyp'Length
5467 function Length_N_Cond
5470 Indx : Nat) return Node_Id;
5471 -- Returns expression to compute:
5472 -- Typ'Length /= Expr'Length
5478 procedure Add_Check (N : Node_Id) is
5482 -- For now, ignore attempt to place more than 2 checks ???
5484 if Num_Checks = 2 then
5488 pragma Assert (Num_Checks <= 1);
5489 Num_Checks := Num_Checks + 1;
5490 Ret_Result (Num_Checks) := N;
5498 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5499 SE : constant Entity_Id := Scope (E);
5501 E1 : Entity_Id := E;
5504 if Ekind (Scope (E)) = E_Record_Type
5505 and then Has_Discriminants (Scope (E))
5507 N := Build_Discriminal_Subtype_Of_Component (E);
5510 Insert_Action (Ck_Node, N);
5511 E1 := Defining_Identifier (N);
5515 if Ekind (E1) = E_String_Literal_Subtype then
5517 Make_Integer_Literal (Loc,
5518 Intval => String_Literal_Length (E1));
5520 elsif SE /= Standard_Standard
5521 and then Ekind (Scope (SE)) = E_Protected_Type
5522 and then Has_Discriminants (Scope (SE))
5523 and then Has_Completion (Scope (SE))
5524 and then not Inside_Init_Proc
5526 -- If the type whose length is needed is a private component
5527 -- constrained by a discriminant, we must expand the 'Length
5528 -- attribute into an explicit computation, using the discriminal
5529 -- of the current protected operation. This is because the actual
5530 -- type of the prival is constructed after the protected opera-
5531 -- tion has been fully expanded.
5534 Indx_Type : Node_Id;
5537 Do_Expand : Boolean := False;
5540 Indx_Type := First_Index (E);
5542 for J in 1 .. Indx - 1 loop
5543 Next_Index (Indx_Type);
5546 Get_Index_Bounds (Indx_Type, Lo, Hi);
5548 if Nkind (Lo) = N_Identifier
5549 and then Ekind (Entity (Lo)) = E_In_Parameter
5551 Lo := Get_Discriminal (E, Lo);
5555 if Nkind (Hi) = N_Identifier
5556 and then Ekind (Entity (Hi)) = E_In_Parameter
5558 Hi := Get_Discriminal (E, Hi);
5563 if not Is_Entity_Name (Lo) then
5564 Lo := Duplicate_Subexpr_No_Checks (Lo);
5567 if not Is_Entity_Name (Hi) then
5568 Lo := Duplicate_Subexpr_No_Checks (Hi);
5574 Make_Op_Subtract (Loc,
5578 Right_Opnd => Make_Integer_Literal (Loc, 1));
5583 Make_Attribute_Reference (Loc,
5584 Attribute_Name => Name_Length,
5586 New_Occurrence_Of (E1, Loc));
5589 Set_Expressions (N, New_List (
5590 Make_Integer_Literal (Loc, Indx)));
5599 Make_Attribute_Reference (Loc,
5600 Attribute_Name => Name_Length,
5602 New_Occurrence_Of (E1, Loc));
5605 Set_Expressions (N, New_List (
5606 Make_Integer_Literal (Loc, Indx)));
5617 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5620 Make_Attribute_Reference (Loc,
5621 Attribute_Name => Name_Length,
5623 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5624 Expressions => New_List (
5625 Make_Integer_Literal (Loc, Indx)));
5632 function Length_E_Cond
5633 (Exptyp : Entity_Id;
5635 Indx : Nat) return Node_Id
5640 Left_Opnd => Get_E_Length (Typ, Indx),
5641 Right_Opnd => Get_E_Length (Exptyp, Indx));
5648 function Length_N_Cond
5651 Indx : Nat) return Node_Id
5656 Left_Opnd => Get_E_Length (Typ, Indx),
5657 Right_Opnd => Get_N_Length (Expr, Indx));
5664 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5667 (Nkind (L) = N_Integer_Literal
5668 and then Nkind (R) = N_Integer_Literal
5669 and then Intval (L) = Intval (R))
5673 and then Ekind (Entity (L)) = E_Constant
5674 and then ((Is_Entity_Name (R)
5675 and then Entity (L) = Entity (R))
5677 (Nkind (R) = N_Type_Conversion
5678 and then Is_Entity_Name (Expression (R))
5679 and then Entity (L) = Entity (Expression (R)))))
5683 and then Ekind (Entity (R)) = E_Constant
5684 and then Nkind (L) = N_Type_Conversion
5685 and then Is_Entity_Name (Expression (L))
5686 and then Entity (R) = Entity (Expression (L)))
5690 and then Is_Entity_Name (R)
5691 and then Entity (L) = Entity (R)
5692 and then Ekind (Entity (L)) = E_In_Parameter
5693 and then Inside_Init_Proc);
5696 -- Start of processing for Selected_Length_Checks
5699 if not Expander_Active then
5703 if Target_Typ = Any_Type
5704 or else Target_Typ = Any_Composite
5705 or else Raises_Constraint_Error (Ck_Node)
5714 T_Typ := Target_Typ;
5716 if No (Source_Typ) then
5717 S_Typ := Etype (Ck_Node);
5719 S_Typ := Source_Typ;
5722 if S_Typ = Any_Type or else S_Typ = Any_Composite then
5726 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
5727 S_Typ := Designated_Type (S_Typ);
5728 T_Typ := Designated_Type (T_Typ);
5731 -- A simple optimization for the null case
5733 if Known_Null (Ck_Node) then
5738 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
5739 if Is_Constrained (T_Typ) then
5741 -- The checking code to be generated will freeze the
5742 -- corresponding array type. However, we must freeze the
5743 -- type now, so that the freeze node does not appear within
5744 -- the generated condional expression, but ahead of it.
5746 Freeze_Before (Ck_Node, T_Typ);
5748 Expr_Actual := Get_Referenced_Object (Ck_Node);
5749 Exptyp := Get_Actual_Subtype (Ck_Node);
5751 if Is_Access_Type (Exptyp) then
5752 Exptyp := Designated_Type (Exptyp);
5755 -- String_Literal case. This needs to be handled specially be-
5756 -- cause no index types are available for string literals. The
5757 -- condition is simply:
5759 -- T_Typ'Length = string-literal-length
5761 if Nkind (Expr_Actual) = N_String_Literal
5762 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
5766 Left_Opnd => Get_E_Length (T_Typ, 1),
5768 Make_Integer_Literal (Loc,
5770 String_Literal_Length (Etype (Expr_Actual))));
5772 -- General array case. Here we have a usable actual subtype for
5773 -- the expression, and the condition is built from the two types
5776 -- T_Typ'Length /= Exptyp'Length or else
5777 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
5778 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
5781 elsif Is_Constrained (Exptyp) then
5783 Ndims : constant Nat := Number_Dimensions (T_Typ);
5796 -- At the library level, we need to ensure that the type of
5797 -- the object is elaborated before the check itself is
5798 -- emitted. This is only done if the object is in the
5799 -- current compilation unit, otherwise the type is frozen
5800 -- and elaborated in its unit.
5802 if Is_Itype (Exptyp)
5804 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
5806 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
5807 and then In_Open_Scopes (Scope (Exptyp))
5809 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
5810 Set_Itype (Ref_Node, Exptyp);
5811 Insert_Action (Ck_Node, Ref_Node);
5814 L_Index := First_Index (T_Typ);
5815 R_Index := First_Index (Exptyp);
5817 for Indx in 1 .. Ndims loop
5818 if not (Nkind (L_Index) = N_Raise_Constraint_Error
5820 Nkind (R_Index) = N_Raise_Constraint_Error)
5822 Get_Index_Bounds (L_Index, L_Low, L_High);
5823 Get_Index_Bounds (R_Index, R_Low, R_High);
5825 -- Deal with compile time length check. Note that we
5826 -- skip this in the access case, because the access
5827 -- value may be null, so we cannot know statically.
5830 and then Compile_Time_Known_Value (L_Low)
5831 and then Compile_Time_Known_Value (L_High)
5832 and then Compile_Time_Known_Value (R_Low)
5833 and then Compile_Time_Known_Value (R_High)
5835 if Expr_Value (L_High) >= Expr_Value (L_Low) then
5836 L_Length := Expr_Value (L_High) -
5837 Expr_Value (L_Low) + 1;
5839 L_Length := UI_From_Int (0);
5842 if Expr_Value (R_High) >= Expr_Value (R_Low) then
5843 R_Length := Expr_Value (R_High) -
5844 Expr_Value (R_Low) + 1;
5846 R_Length := UI_From_Int (0);
5849 if L_Length > R_Length then
5851 (Compile_Time_Constraint_Error
5852 (Wnode, "too few elements for}?", T_Typ));
5854 elsif L_Length < R_Length then
5856 (Compile_Time_Constraint_Error
5857 (Wnode, "too many elements for}?", T_Typ));
5860 -- The comparison for an individual index subtype
5861 -- is omitted if the corresponding index subtypes
5862 -- statically match, since the result is known to
5863 -- be true. Note that this test is worth while even
5864 -- though we do static evaluation, because non-static
5865 -- subtypes can statically match.
5868 Subtypes_Statically_Match
5869 (Etype (L_Index), Etype (R_Index))
5872 (Same_Bounds (L_Low, R_Low)
5873 and then Same_Bounds (L_High, R_High))
5876 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
5885 -- Handle cases where we do not get a usable actual subtype that
5886 -- is constrained. This happens for example in the function call
5887 -- and explicit dereference cases. In these cases, we have to get
5888 -- the length or range from the expression itself, making sure we
5889 -- do not evaluate it more than once.
5891 -- Here Ck_Node is the original expression, or more properly the
5892 -- result of applying Duplicate_Expr to the original tree, forcing
5893 -- the result to be a name.
5897 Ndims : constant Nat := Number_Dimensions (T_Typ);
5900 -- Build the condition for the explicit dereference case
5902 for Indx in 1 .. Ndims loop
5904 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
5911 -- Construct the test and insert into the tree
5913 if Present (Cond) then
5915 Cond := Guard_Access (Cond, Loc, Ck_Node);
5919 (Make_Raise_Constraint_Error (Loc,
5921 Reason => CE_Length_Check_Failed));
5925 end Selected_Length_Checks;
5927 ---------------------------
5928 -- Selected_Range_Checks --
5929 ---------------------------
5931 function Selected_Range_Checks
5933 Target_Typ : Entity_Id;
5934 Source_Typ : Entity_Id;
5935 Warn_Node : Node_Id) return Check_Result
5937 Loc : constant Source_Ptr := Sloc (Ck_Node);
5940 Expr_Actual : Node_Id;
5942 Cond : Node_Id := Empty;
5943 Do_Access : Boolean := False;
5944 Wnode : Node_Id := Warn_Node;
5945 Ret_Result : Check_Result := (Empty, Empty);
5946 Num_Checks : Integer := 0;
5948 procedure Add_Check (N : Node_Id);
5949 -- Adds the action given to Ret_Result if N is non-Empty
5951 function Discrete_Range_Cond
5953 Typ : Entity_Id) return Node_Id;
5954 -- Returns expression to compute:
5955 -- Low_Bound (Expr) < Typ'First
5957 -- High_Bound (Expr) > Typ'Last
5959 function Discrete_Expr_Cond
5961 Typ : Entity_Id) return Node_Id;
5962 -- Returns expression to compute:
5967 function Get_E_First_Or_Last
5970 Nam : Name_Id) return Node_Id;
5971 -- Returns expression to compute:
5972 -- E'First or E'Last
5974 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
5975 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
5976 -- Returns expression to compute:
5977 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
5979 function Range_E_Cond
5980 (Exptyp : Entity_Id;
5984 -- Returns expression to compute:
5985 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
5987 function Range_Equal_E_Cond
5988 (Exptyp : Entity_Id;
5990 Indx : Nat) return Node_Id;
5991 -- Returns expression to compute:
5992 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
5994 function Range_N_Cond
5997 Indx : Nat) return Node_Id;
5998 -- Return expression to compute:
5999 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
6005 procedure Add_Check (N : Node_Id) is
6009 -- For now, ignore attempt to place more than 2 checks ???
6011 if Num_Checks = 2 then
6015 pragma Assert (Num_Checks <= 1);
6016 Num_Checks := Num_Checks + 1;
6017 Ret_Result (Num_Checks) := N;
6021 -------------------------
6022 -- Discrete_Expr_Cond --
6023 -------------------------
6025 function Discrete_Expr_Cond
6027 Typ : Entity_Id) return Node_Id
6035 Convert_To (Base_Type (Typ),
6036 Duplicate_Subexpr_No_Checks (Expr)),
6038 Convert_To (Base_Type (Typ),
6039 Get_E_First_Or_Last (Typ, 0, Name_First))),
6044 Convert_To (Base_Type (Typ),
6045 Duplicate_Subexpr_No_Checks (Expr)),
6049 Get_E_First_Or_Last (Typ, 0, Name_Last))));
6050 end Discrete_Expr_Cond;
6052 -------------------------
6053 -- Discrete_Range_Cond --
6054 -------------------------
6056 function Discrete_Range_Cond
6058 Typ : Entity_Id) return Node_Id
6060 LB : Node_Id := Low_Bound (Expr);
6061 HB : Node_Id := High_Bound (Expr);
6063 Left_Opnd : Node_Id;
6064 Right_Opnd : Node_Id;
6067 if Nkind (LB) = N_Identifier
6068 and then Ekind (Entity (LB)) = E_Discriminant
6070 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6073 if Nkind (HB) = N_Identifier
6074 and then Ekind (Entity (HB)) = E_Discriminant
6076 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6083 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6087 (Base_Type (Typ), Get_E_First_Or_Last (Typ, 0, Name_First)));
6089 if Base_Type (Typ) = Typ then
6092 elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6094 Compile_Time_Known_Value (High_Bound (Scalar_Range
6097 if Is_Floating_Point_Type (Typ) then
6098 if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6099 Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6105 if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6106 Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6117 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6122 Get_E_First_Or_Last (Typ, 0, Name_Last)));
6124 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6125 end Discrete_Range_Cond;
6127 -------------------------
6128 -- Get_E_First_Or_Last --
6129 -------------------------
6131 function Get_E_First_Or_Last
6134 Nam : Name_Id) return Node_Id
6142 if Is_Array_Type (E) then
6143 N := First_Index (E);
6145 for J in 2 .. Indx loop
6150 N := Scalar_Range (E);
6153 if Nkind (N) = N_Subtype_Indication then
6154 LB := Low_Bound (Range_Expression (Constraint (N)));
6155 HB := High_Bound (Range_Expression (Constraint (N)));
6157 elsif Is_Entity_Name (N) then
6158 LB := Type_Low_Bound (Etype (N));
6159 HB := Type_High_Bound (Etype (N));
6162 LB := Low_Bound (N);
6163 HB := High_Bound (N);
6166 if Nam = Name_First then
6172 if Nkind (Bound) = N_Identifier
6173 and then Ekind (Entity (Bound)) = E_Discriminant
6175 -- If this is a task discriminant, and we are the body, we must
6176 -- retrieve the corresponding body discriminal. This is another
6177 -- consequence of the early creation of discriminals, and the
6178 -- need to generate constraint checks before their declarations
6179 -- are made visible.
6181 if Is_Concurrent_Record_Type (Scope (Entity (Bound))) then
6183 Tsk : constant Entity_Id :=
6184 Corresponding_Concurrent_Type
6185 (Scope (Entity (Bound)));
6189 if In_Open_Scopes (Tsk)
6190 and then Has_Completion (Tsk)
6192 -- Find discriminant of original task, and use its
6193 -- current discriminal, which is the renaming within
6196 Disc := First_Discriminant (Tsk);
6197 while Present (Disc) loop
6198 if Chars (Disc) = Chars (Entity (Bound)) then
6199 Set_Scope (Discriminal (Disc), Tsk);
6200 return New_Occurrence_Of (Discriminal (Disc), Loc);
6203 Next_Discriminant (Disc);
6206 -- That loop should always succeed in finding a matching
6207 -- entry and returning. Fatal error if not.
6209 raise Program_Error;
6213 New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6217 return New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6220 elsif Nkind (Bound) = N_Identifier
6221 and then Ekind (Entity (Bound)) = E_In_Parameter
6222 and then not Inside_Init_Proc
6224 return Get_Discriminal (E, Bound);
6226 elsif Nkind (Bound) = N_Integer_Literal then
6227 return Make_Integer_Literal (Loc, Intval (Bound));
6229 -- Case of a bound rewritten to an N_Raise_Constraint_Error node
6230 -- because it is an out-of-range value. Duplicate_Subexpr cannot be
6231 -- called on this node because an N_Raise_Constraint_Error is not
6232 -- side effect free, and we may not assume that we are in the proper
6233 -- context to remove side effects on it at the point of reference.
6235 elsif Nkind (Bound) = N_Raise_Constraint_Error then
6236 return New_Copy_Tree (Bound);
6239 return Duplicate_Subexpr_No_Checks (Bound);
6241 end Get_E_First_Or_Last;
6247 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6250 Make_Attribute_Reference (Loc,
6251 Attribute_Name => Name_First,
6253 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6254 Expressions => New_List (
6255 Make_Integer_Literal (Loc, Indx)));
6262 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6265 Make_Attribute_Reference (Loc,
6266 Attribute_Name => Name_Last,
6268 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6269 Expressions => New_List (
6270 Make_Integer_Literal (Loc, Indx)));
6277 function Range_E_Cond
6278 (Exptyp : Entity_Id;
6280 Indx : Nat) return Node_Id
6287 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6288 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6292 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6293 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6296 ------------------------
6297 -- Range_Equal_E_Cond --
6298 ------------------------
6300 function Range_Equal_E_Cond
6301 (Exptyp : Entity_Id;
6303 Indx : Nat) return Node_Id
6310 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6311 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6314 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6315 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6316 end Range_Equal_E_Cond;
6322 function Range_N_Cond
6325 Indx : Nat) return Node_Id
6332 Left_Opnd => Get_N_First (Expr, Indx),
6333 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6337 Left_Opnd => Get_N_Last (Expr, Indx),
6338 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6341 -- Start of processing for Selected_Range_Checks
6344 if not Expander_Active then
6348 if Target_Typ = Any_Type
6349 or else Target_Typ = Any_Composite
6350 or else Raises_Constraint_Error (Ck_Node)
6359 T_Typ := Target_Typ;
6361 if No (Source_Typ) then
6362 S_Typ := Etype (Ck_Node);
6364 S_Typ := Source_Typ;
6367 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6371 -- The order of evaluating T_Typ before S_Typ seems to be critical
6372 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6373 -- in, and since Node can be an N_Range node, it might be invalid.
6374 -- Should there be an assert check somewhere for taking the Etype of
6375 -- an N_Range node ???
6377 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6378 S_Typ := Designated_Type (S_Typ);
6379 T_Typ := Designated_Type (T_Typ);
6382 -- A simple optimization for the null case
6384 if Known_Null (Ck_Node) then
6389 -- For an N_Range Node, check for a null range and then if not
6390 -- null generate a range check action.
6392 if Nkind (Ck_Node) = N_Range then
6394 -- There's no point in checking a range against itself
6396 if Ck_Node = Scalar_Range (T_Typ) then
6401 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
6402 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
6403 LB : constant Node_Id := Low_Bound (Ck_Node);
6404 HB : constant Node_Id := High_Bound (Ck_Node);
6405 Null_Range : Boolean;
6407 Out_Of_Range_L : Boolean;
6408 Out_Of_Range_H : Boolean;
6411 -- Check for case where everything is static and we can
6412 -- do the check at compile time. This is skipped if we
6413 -- have an access type, since the access value may be null.
6415 -- ??? This code can be improved since you only need to know
6416 -- that the two respective bounds (LB & T_LB or HB & T_HB)
6417 -- are known at compile time to emit pertinent messages.
6419 if Compile_Time_Known_Value (LB)
6420 and then Compile_Time_Known_Value (HB)
6421 and then Compile_Time_Known_Value (T_LB)
6422 and then Compile_Time_Known_Value (T_HB)
6423 and then not Do_Access
6425 -- Floating-point case
6427 if Is_Floating_Point_Type (S_Typ) then
6428 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6430 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6432 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6435 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6437 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6439 -- Fixed or discrete type case
6442 Null_Range := Expr_Value (HB) < Expr_Value (LB);
6444 (Expr_Value (LB) < Expr_Value (T_LB))
6446 (Expr_Value (LB) > Expr_Value (T_HB));
6449 (Expr_Value (HB) > Expr_Value (T_HB))
6451 (Expr_Value (HB) < Expr_Value (T_LB));
6454 if not Null_Range then
6455 if Out_Of_Range_L then
6456 if No (Warn_Node) then
6458 (Compile_Time_Constraint_Error
6459 (Low_Bound (Ck_Node),
6460 "static value out of range of}?", T_Typ));
6464 (Compile_Time_Constraint_Error
6466 "static range out of bounds of}?", T_Typ));
6470 if Out_Of_Range_H then
6471 if No (Warn_Node) then
6473 (Compile_Time_Constraint_Error
6474 (High_Bound (Ck_Node),
6475 "static value out of range of}?", T_Typ));
6479 (Compile_Time_Constraint_Error
6481 "static range out of bounds of}?", T_Typ));
6489 LB : Node_Id := Low_Bound (Ck_Node);
6490 HB : Node_Id := High_Bound (Ck_Node);
6493 -- If either bound is a discriminant and we are within the
6494 -- record declaration, it is a use of the discriminant in a
6495 -- constraint of a component, and nothing can be checked
6496 -- here. The check will be emitted within the init proc.
6497 -- Before then, the discriminal has no real meaning.
6498 -- Similarly, if the entity is a discriminal, there is no
6499 -- check to perform yet.
6501 -- The same holds within a discriminated synchronized type,
6502 -- where the discriminant may constrain a component or an
6505 if Nkind (LB) = N_Identifier
6506 and then Denotes_Discriminant (LB, True)
6508 if Current_Scope = Scope (Entity (LB))
6509 or else Is_Concurrent_Type (Current_Scope)
6510 or else Ekind (Entity (LB)) /= E_Discriminant
6515 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6519 if Nkind (HB) = N_Identifier
6520 and then Denotes_Discriminant (HB, True)
6522 if Current_Scope = Scope (Entity (HB))
6523 or else Is_Concurrent_Type (Current_Scope)
6524 or else Ekind (Entity (HB)) /= E_Discriminant
6529 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6533 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6534 Set_Paren_Count (Cond, 1);
6540 Left_Opnd => Duplicate_Subexpr_No_Checks (HB),
6541 Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6542 Right_Opnd => Cond);
6547 elsif Is_Scalar_Type (S_Typ) then
6549 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
6550 -- except the above simply sets a flag in the node and lets
6551 -- gigi generate the check base on the Etype of the expression.
6552 -- Sometimes, however we want to do a dynamic check against an
6553 -- arbitrary target type, so we do that here.
6555 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6556 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6558 -- For literals, we can tell if the constraint error will be
6559 -- raised at compile time, so we never need a dynamic check, but
6560 -- if the exception will be raised, then post the usual warning,
6561 -- and replace the literal with a raise constraint error
6562 -- expression. As usual, skip this for access types
6564 elsif Compile_Time_Known_Value (Ck_Node)
6565 and then not Do_Access
6568 LB : constant Node_Id := Type_Low_Bound (T_Typ);
6569 UB : constant Node_Id := Type_High_Bound (T_Typ);
6571 Out_Of_Range : Boolean;
6572 Static_Bounds : constant Boolean :=
6573 Compile_Time_Known_Value (LB)
6574 and Compile_Time_Known_Value (UB);
6577 -- Following range tests should use Sem_Eval routine ???
6579 if Static_Bounds then
6580 if Is_Floating_Point_Type (S_Typ) then
6582 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6584 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6586 else -- fixed or discrete type
6588 Expr_Value (Ck_Node) < Expr_Value (LB)
6590 Expr_Value (Ck_Node) > Expr_Value (UB);
6593 -- Bounds of the type are static and the literal is
6594 -- out of range so make a warning message.
6596 if Out_Of_Range then
6597 if No (Warn_Node) then
6599 (Compile_Time_Constraint_Error
6601 "static value out of range of}?", T_Typ));
6605 (Compile_Time_Constraint_Error
6607 "static value out of range of}?", T_Typ));
6612 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6616 -- Here for the case of a non-static expression, we need a runtime
6617 -- check unless the source type range is guaranteed to be in the
6618 -- range of the target type.
6621 if not In_Subrange_Of (S_Typ, T_Typ) then
6622 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6627 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6628 if Is_Constrained (T_Typ) then
6630 Expr_Actual := Get_Referenced_Object (Ck_Node);
6631 Exptyp := Get_Actual_Subtype (Expr_Actual);
6633 if Is_Access_Type (Exptyp) then
6634 Exptyp := Designated_Type (Exptyp);
6637 -- String_Literal case. This needs to be handled specially be-
6638 -- cause no index types are available for string literals. The
6639 -- condition is simply:
6641 -- T_Typ'Length = string-literal-length
6643 if Nkind (Expr_Actual) = N_String_Literal then
6646 -- General array case. Here we have a usable actual subtype for
6647 -- the expression, and the condition is built from the two types
6649 -- T_Typ'First < Exptyp'First or else
6650 -- T_Typ'Last > Exptyp'Last or else
6651 -- T_Typ'First(1) < Exptyp'First(1) or else
6652 -- T_Typ'Last(1) > Exptyp'Last(1) or else
6655 elsif Is_Constrained (Exptyp) then
6657 Ndims : constant Nat := Number_Dimensions (T_Typ);
6667 L_Index := First_Index (T_Typ);
6668 R_Index := First_Index (Exptyp);
6670 for Indx in 1 .. Ndims loop
6671 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6673 Nkind (R_Index) = N_Raise_Constraint_Error)
6675 Get_Index_Bounds (L_Index, L_Low, L_High);
6676 Get_Index_Bounds (R_Index, R_Low, R_High);
6678 -- Deal with compile time length check. Note that we
6679 -- skip this in the access case, because the access
6680 -- value may be null, so we cannot know statically.
6683 Subtypes_Statically_Match
6684 (Etype (L_Index), Etype (R_Index))
6686 -- If the target type is constrained then we
6687 -- have to check for exact equality of bounds
6688 -- (required for qualified expressions).
6690 if Is_Constrained (T_Typ) then
6693 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6697 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6708 -- Handle cases where we do not get a usable actual subtype that
6709 -- is constrained. This happens for example in the function call
6710 -- and explicit dereference cases. In these cases, we have to get
6711 -- the length or range from the expression itself, making sure we
6712 -- do not evaluate it more than once.
6714 -- Here Ck_Node is the original expression, or more properly the
6715 -- result of applying Duplicate_Expr to the original tree,
6716 -- forcing the result to be a name.
6720 Ndims : constant Nat := Number_Dimensions (T_Typ);
6723 -- Build the condition for the explicit dereference case
6725 for Indx in 1 .. Ndims loop
6727 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
6734 -- For a conversion to an unconstrained array type, generate an
6735 -- Action to check that the bounds of the source value are within
6736 -- the constraints imposed by the target type (RM 4.6(38)). No
6737 -- check is needed for a conversion to an access to unconstrained
6738 -- array type, as 4.6(24.15/2) requires the designated subtypes
6739 -- of the two access types to statically match.
6741 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
6742 and then not Do_Access
6745 Opnd_Index : Node_Id;
6746 Targ_Index : Node_Id;
6747 Opnd_Range : Node_Id;
6750 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
6751 Targ_Index := First_Index (T_Typ);
6753 while Present (Opnd_Index) loop
6755 -- If the index is a range, use its bounds. If it is an
6756 -- entity (as will be the case if it is a named subtype
6757 -- or an itype created for a slice) retrieve its range.
6759 if Is_Entity_Name (Opnd_Index)
6760 and then Is_Type (Entity (Opnd_Index))
6762 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
6764 Opnd_Range := Opnd_Index;
6767 if Nkind (Opnd_Range) = N_Range then
6769 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6772 (High_Bound (Opnd_Range), Etype (Targ_Index))
6776 -- If null range, no check needed
6779 Compile_Time_Known_Value (High_Bound (Opnd_Range))
6781 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
6783 Expr_Value (High_Bound (Opnd_Range)) <
6784 Expr_Value (Low_Bound (Opnd_Range))
6788 elsif Is_Out_Of_Range
6789 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6792 (High_Bound (Opnd_Range), Etype (Targ_Index))
6795 (Compile_Time_Constraint_Error
6796 (Wnode, "value out of range of}?", T_Typ));
6802 (Opnd_Range, Etype (Targ_Index)));
6806 Next_Index (Opnd_Index);
6807 Next_Index (Targ_Index);
6814 -- Construct the test and insert into the tree
6816 if Present (Cond) then
6818 Cond := Guard_Access (Cond, Loc, Ck_Node);
6822 (Make_Raise_Constraint_Error (Loc,
6824 Reason => CE_Range_Check_Failed));
6828 end Selected_Range_Checks;
6830 -------------------------------
6831 -- Storage_Checks_Suppressed --
6832 -------------------------------
6834 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
6836 if Present (E) and then Checks_May_Be_Suppressed (E) then
6837 return Is_Check_Suppressed (E, Storage_Check);
6839 return Scope_Suppress (Storage_Check);
6841 end Storage_Checks_Suppressed;
6843 ---------------------------
6844 -- Tag_Checks_Suppressed --
6845 ---------------------------
6847 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
6850 if Kill_Tag_Checks (E) then
6852 elsif Checks_May_Be_Suppressed (E) then
6853 return Is_Check_Suppressed (E, Tag_Check);
6857 return Scope_Suppress (Tag_Check);
6858 end Tag_Checks_Suppressed;
6860 --------------------------
6861 -- Validity_Check_Range --
6862 --------------------------
6864 procedure Validity_Check_Range (N : Node_Id) is
6866 if Validity_Checks_On and Validity_Check_Operands then
6867 if Nkind (N) = N_Range then
6868 Ensure_Valid (Low_Bound (N));
6869 Ensure_Valid (High_Bound (N));
6872 end Validity_Check_Range;
6874 --------------------------------
6875 -- Validity_Checks_Suppressed --
6876 --------------------------------
6878 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
6880 if Present (E) and then Checks_May_Be_Suppressed (E) then
6881 return Is_Check_Suppressed (E, Validity_Check);
6883 return Scope_Suppress (Validity_Check);
6885 end Validity_Checks_Suppressed;