2014-09-15 Andreas Krebbel <Andreas.Krebbel@de.ibm.com>
[official-gcc.git] / gcc / ada / checks.adb
blob05f4b7e476ae1e53a37fe4a4ec3e2fa98683782e
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- C H E C K S --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2014, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
26 with Atree; use Atree;
27 with Casing; use Casing;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Elists; use Elists;
31 with Eval_Fat; use Eval_Fat;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Ch2; use Exp_Ch2;
34 with Exp_Ch4; use Exp_Ch4;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Util; use Exp_Util;
37 with Expander; use Expander;
38 with Freeze; use Freeze;
39 with Lib; use Lib;
40 with Nlists; use Nlists;
41 with Nmake; use Nmake;
42 with Opt; use Opt;
43 with Output; use Output;
44 with Restrict; use Restrict;
45 with Rident; use Rident;
46 with Rtsfind; use Rtsfind;
47 with Sem; use Sem;
48 with Sem_Aux; use Sem_Aux;
49 with Sem_Ch3; use Sem_Ch3;
50 with Sem_Ch8; use Sem_Ch8;
51 with Sem_Eval; use Sem_Eval;
52 with Sem_Res; use Sem_Res;
53 with Sem_Util; use Sem_Util;
54 with Sem_Warn; use Sem_Warn;
55 with Sinfo; use Sinfo;
56 with Sinput; use Sinput;
57 with Snames; use Snames;
58 with Sprint; use Sprint;
59 with Stand; use Stand;
60 with Stringt; use Stringt;
61 with Targparm; use Targparm;
62 with Tbuild; use Tbuild;
63 with Ttypes; use Ttypes;
64 with Validsw; use Validsw;
66 package body Checks is
68 -- General note: many of these routines are concerned with generating
69 -- checking code to make sure that constraint error is raised at runtime.
70 -- Clearly this code is only needed if the expander is active, since
71 -- otherwise we will not be generating code or going into the runtime
72 -- execution anyway.
74 -- We therefore disconnect most of these checks if the expander is
75 -- inactive. This has the additional benefit that we do not need to
76 -- worry about the tree being messed up by previous errors (since errors
77 -- turn off expansion anyway).
79 -- There are a few exceptions to the above rule. For instance routines
80 -- such as Apply_Scalar_Range_Check that do not insert any code can be
81 -- safely called even when the Expander is inactive (but Errors_Detected
82 -- is 0). The benefit of executing this code when expansion is off, is
83 -- the ability to emit constraint error warning for static expressions
84 -- even when we are not generating code.
86 -- The above is modified in gnatprove mode to ensure that proper check
87 -- flags are always placed, even if expansion is off.
89 -------------------------------------
90 -- Suppression of Redundant Checks --
91 -------------------------------------
93 -- This unit implements a limited circuit for removal of redundant
94 -- checks. The processing is based on a tracing of simple sequential
95 -- flow. For any sequence of statements, we save expressions that are
96 -- marked to be checked, and then if the same expression appears later
97 -- with the same check, then under certain circumstances, the second
98 -- check can be suppressed.
100 -- Basically, we can suppress the check if we know for certain that
101 -- the previous expression has been elaborated (together with its
102 -- check), and we know that the exception frame is the same, and that
103 -- nothing has happened to change the result of the exception.
105 -- Let us examine each of these three conditions in turn to describe
106 -- how we ensure that this condition is met.
108 -- First, we need to know for certain that the previous expression has
109 -- been executed. This is done principally by the mechanism of calling
110 -- Conditional_Statements_Begin at the start of any statement sequence
111 -- and Conditional_Statements_End at the end. The End call causes all
112 -- checks remembered since the Begin call to be discarded. This does
113 -- miss a few cases, notably the case of a nested BEGIN-END block with
114 -- no exception handlers. But the important thing is to be conservative.
115 -- The other protection is that all checks are discarded if a label
116 -- is encountered, since then the assumption of sequential execution
117 -- is violated, and we don't know enough about the flow.
119 -- Second, we need to know that the exception frame is the same. We
120 -- do this by killing all remembered checks when we enter a new frame.
121 -- Again, that's over-conservative, but generally the cases we can help
122 -- with are pretty local anyway (like the body of a loop for example).
124 -- Third, we must be sure to forget any checks which are no longer valid.
125 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
126 -- used to note any changes to local variables. We only attempt to deal
127 -- with checks involving local variables, so we do not need to worry
128 -- about global variables. Second, a call to any non-global procedure
129 -- causes us to abandon all stored checks, since such a all may affect
130 -- the values of any local variables.
132 -- The following define the data structures used to deal with remembering
133 -- checks so that redundant checks can be eliminated as described above.
135 -- Right now, the only expressions that we deal with are of the form of
136 -- simple local objects (either declared locally, or IN parameters) or
137 -- such objects plus/minus a compile time known constant. We can do
138 -- more later on if it seems worthwhile, but this catches many simple
139 -- cases in practice.
141 -- The following record type reflects a single saved check. An entry
142 -- is made in the stack of saved checks if and only if the expression
143 -- has been elaborated with the indicated checks.
145 type Saved_Check is record
146 Killed : Boolean;
147 -- Set True if entry is killed by Kill_Checks
149 Entity : Entity_Id;
150 -- The entity involved in the expression that is checked
152 Offset : Uint;
153 -- A compile time value indicating the result of adding or
154 -- subtracting a compile time value. This value is to be
155 -- added to the value of the Entity. A value of zero is
156 -- used for the case of a simple entity reference.
158 Check_Type : Character;
159 -- This is set to 'R' for a range check (in which case Target_Type
160 -- is set to the target type for the range check) or to 'O' for an
161 -- overflow check (in which case Target_Type is set to Empty).
163 Target_Type : Entity_Id;
164 -- Used only if Do_Range_Check is set. Records the target type for
165 -- the check. We need this, because a check is a duplicate only if
166 -- it has the same target type (or more accurately one with a
167 -- range that is smaller or equal to the stored target type of a
168 -- saved check).
169 end record;
171 -- The following table keeps track of saved checks. Rather than use an
172 -- extensible table. We just use a table of fixed size, and we discard
173 -- any saved checks that do not fit. That's very unlikely to happen and
174 -- this is only an optimization in any case.
176 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
177 -- Array of saved checks
179 Num_Saved_Checks : Nat := 0;
180 -- Number of saved checks
182 -- The following stack keeps track of statement ranges. It is treated
183 -- as a stack. When Conditional_Statements_Begin is called, an entry
184 -- is pushed onto this stack containing the value of Num_Saved_Checks
185 -- at the time of the call. Then when Conditional_Statements_End is
186 -- called, this value is popped off and used to reset Num_Saved_Checks.
188 -- Note: again, this is a fixed length stack with a size that should
189 -- always be fine. If the value of the stack pointer goes above the
190 -- limit, then we just forget all saved checks.
192 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
193 Saved_Checks_TOS : Nat := 0;
195 -----------------------
196 -- Local Subprograms --
197 -----------------------
199 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id);
200 -- Used to apply arithmetic overflow checks for all cases except operators
201 -- on signed arithmetic types in MINIMIZED/ELIMINATED case (for which we
202 -- call Apply_Arithmetic_Overflow_Minimized_Eliminated below). N can be a
203 -- signed integer arithmetic operator (but not an if or case expression).
204 -- It is also called for types other than signed integers.
206 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id);
207 -- Used to apply arithmetic overflow checks for the case where the overflow
208 -- checking mode is MINIMIZED or ELIMINATED and we have a signed integer
209 -- arithmetic op (which includes the case of if and case expressions). Note
210 -- that Do_Overflow_Check may or may not be set for node Op. In these modes
211 -- we have work to do even if overflow checking is suppressed.
213 procedure Apply_Division_Check
214 (N : Node_Id;
215 Rlo : Uint;
216 Rhi : Uint;
217 ROK : Boolean);
218 -- N is an N_Op_Div, N_Op_Rem, or N_Op_Mod node. This routine applies
219 -- division checks as required if the Do_Division_Check flag is set.
220 -- Rlo and Rhi give the possible range of the right operand, these values
221 -- can be referenced and trusted only if ROK is set True.
223 procedure Apply_Float_Conversion_Check
224 (Ck_Node : Node_Id;
225 Target_Typ : Entity_Id);
226 -- The checks on a conversion from a floating-point type to an integer
227 -- type are delicate. They have to be performed before conversion, they
228 -- have to raise an exception when the operand is a NaN, and rounding must
229 -- be taken into account to determine the safe bounds of the operand.
231 procedure Apply_Selected_Length_Checks
232 (Ck_Node : Node_Id;
233 Target_Typ : Entity_Id;
234 Source_Typ : Entity_Id;
235 Do_Static : Boolean);
236 -- This is the subprogram that does all the work for Apply_Length_Check
237 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
238 -- described for the above routines. The Do_Static flag indicates that
239 -- only a static check is to be done.
241 procedure Apply_Selected_Range_Checks
242 (Ck_Node : Node_Id;
243 Target_Typ : Entity_Id;
244 Source_Typ : Entity_Id;
245 Do_Static : Boolean);
246 -- This is the subprogram that does all the work for Apply_Range_Check.
247 -- Expr, Target_Typ and Source_Typ are as described for the above
248 -- routine. The Do_Static flag indicates that only a static check is
249 -- to be done.
251 type Check_Type is new Check_Id range Access_Check .. Division_Check;
252 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
253 -- This function is used to see if an access or division by zero check is
254 -- needed. The check is to be applied to a single variable appearing in the
255 -- source, and N is the node for the reference. If N is not of this form,
256 -- True is returned with no further processing. If N is of the right form,
257 -- then further processing determines if the given Check is needed.
259 -- The particular circuit is to see if we have the case of a check that is
260 -- not needed because it appears in the right operand of a short circuited
261 -- conditional where the left operand guards the check. For example:
263 -- if Var = 0 or else Q / Var > 12 then
264 -- ...
265 -- end if;
267 -- In this example, the division check is not required. At the same time
268 -- we can issue warnings for suspicious use of non-short-circuited forms,
269 -- such as:
271 -- if Var = 0 or Q / Var > 12 then
272 -- ...
273 -- end if;
275 procedure Find_Check
276 (Expr : Node_Id;
277 Check_Type : Character;
278 Target_Type : Entity_Id;
279 Entry_OK : out Boolean;
280 Check_Num : out Nat;
281 Ent : out Entity_Id;
282 Ofs : out Uint);
283 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
284 -- to see if a check is of the form for optimization, and if so, to see
285 -- if it has already been performed. Expr is the expression to check,
286 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
287 -- Target_Type is the target type for a range check, and Empty for an
288 -- overflow check. If the entry is not of the form for optimization,
289 -- then Entry_OK is set to False, and the remaining out parameters
290 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
291 -- entity and offset from the expression. Check_Num is the number of
292 -- a matching saved entry in Saved_Checks, or zero if no such entry
293 -- is located.
295 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
296 -- If a discriminal is used in constraining a prival, Return reference
297 -- to the discriminal of the protected body (which renames the parameter
298 -- of the enclosing protected operation). This clumsy transformation is
299 -- needed because privals are created too late and their actual subtypes
300 -- are not available when analysing the bodies of the protected operations.
301 -- This function is called whenever the bound is an entity and the scope
302 -- indicates a protected operation. If the bound is an in-parameter of
303 -- a protected operation that is not a prival, the function returns the
304 -- bound itself.
305 -- To be cleaned up???
307 function Guard_Access
308 (Cond : Node_Id;
309 Loc : Source_Ptr;
310 Ck_Node : Node_Id) return Node_Id;
311 -- In the access type case, guard the test with a test to ensure
312 -- that the access value is non-null, since the checks do not
313 -- not apply to null access values.
315 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
316 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
317 -- Constraint_Error node.
319 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean;
320 -- Returns True if node N is for an arithmetic operation with signed
321 -- integer operands. This includes unary and binary operators, and also
322 -- if and case expression nodes where the dependent expressions are of
323 -- a signed integer type. These are the kinds of nodes for which special
324 -- handling applies in MINIMIZED or ELIMINATED overflow checking mode.
326 function Range_Or_Validity_Checks_Suppressed
327 (Expr : Node_Id) return Boolean;
328 -- Returns True if either range or validity checks or both are suppressed
329 -- for the type of the given expression, or, if the expression is the name
330 -- of an entity, if these checks are suppressed for the entity.
332 function Selected_Length_Checks
333 (Ck_Node : Node_Id;
334 Target_Typ : Entity_Id;
335 Source_Typ : Entity_Id;
336 Warn_Node : Node_Id) return Check_Result;
337 -- Like Apply_Selected_Length_Checks, except it doesn't modify
338 -- anything, just returns a list of nodes as described in the spec of
339 -- this package for the Range_Check function.
341 function Selected_Range_Checks
342 (Ck_Node : Node_Id;
343 Target_Typ : Entity_Id;
344 Source_Typ : Entity_Id;
345 Warn_Node : Node_Id) return Check_Result;
346 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
347 -- just returns a list of nodes as described in the spec of this package
348 -- for the Range_Check function.
350 ------------------------------
351 -- Access_Checks_Suppressed --
352 ------------------------------
354 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
355 begin
356 if Present (E) and then Checks_May_Be_Suppressed (E) then
357 return Is_Check_Suppressed (E, Access_Check);
358 else
359 return Scope_Suppress.Suppress (Access_Check);
360 end if;
361 end Access_Checks_Suppressed;
363 -------------------------------------
364 -- Accessibility_Checks_Suppressed --
365 -------------------------------------
367 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
368 begin
369 if Present (E) and then Checks_May_Be_Suppressed (E) then
370 return Is_Check_Suppressed (E, Accessibility_Check);
371 else
372 return Scope_Suppress.Suppress (Accessibility_Check);
373 end if;
374 end Accessibility_Checks_Suppressed;
376 -----------------------------
377 -- Activate_Division_Check --
378 -----------------------------
380 procedure Activate_Division_Check (N : Node_Id) is
381 begin
382 Set_Do_Division_Check (N, True);
383 Possible_Local_Raise (N, Standard_Constraint_Error);
384 end Activate_Division_Check;
386 -----------------------------
387 -- Activate_Overflow_Check --
388 -----------------------------
390 procedure Activate_Overflow_Check (N : Node_Id) is
391 Typ : constant Entity_Id := Etype (N);
393 begin
394 -- Floating-point case. If Etype is not set (this can happen when we
395 -- activate a check on a node that has not yet been analyzed), then
396 -- we assume we do not have a floating-point type (as per our spec).
398 if Present (Typ) and then Is_Floating_Point_Type (Typ) then
400 -- Ignore call if we have no automatic overflow checks on the target
401 -- and Check_Float_Overflow mode is not set. These are the cases in
402 -- which we expect to generate infinities and NaN's with no check.
404 if not (Machine_Overflows_On_Target or Check_Float_Overflow) then
405 return;
407 -- Ignore for unary operations ("+", "-", abs) since these can never
408 -- result in overflow for floating-point cases.
410 elsif Nkind (N) in N_Unary_Op then
411 return;
413 -- Otherwise we will set the flag
415 else
416 null;
417 end if;
419 -- Discrete case
421 else
422 -- Nothing to do for Rem/Mod/Plus (overflow not possible, the check
423 -- for zero-divide is a divide check, not an overflow check).
425 if Nkind_In (N, N_Op_Rem, N_Op_Mod, N_Op_Plus) then
426 return;
427 end if;
428 end if;
430 -- Fall through for cases where we do set the flag
432 Set_Do_Overflow_Check (N, True);
433 Possible_Local_Raise (N, Standard_Constraint_Error);
434 end Activate_Overflow_Check;
436 --------------------------
437 -- Activate_Range_Check --
438 --------------------------
440 procedure Activate_Range_Check (N : Node_Id) is
441 begin
442 Set_Do_Range_Check (N, True);
443 Possible_Local_Raise (N, Standard_Constraint_Error);
444 end Activate_Range_Check;
446 ---------------------------------
447 -- Alignment_Checks_Suppressed --
448 ---------------------------------
450 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
451 begin
452 if Present (E) and then Checks_May_Be_Suppressed (E) then
453 return Is_Check_Suppressed (E, Alignment_Check);
454 else
455 return Scope_Suppress.Suppress (Alignment_Check);
456 end if;
457 end Alignment_Checks_Suppressed;
459 ----------------------------------
460 -- Allocation_Checks_Suppressed --
461 ----------------------------------
463 -- Note: at the current time there are no calls to this function, because
464 -- the relevant check is in the run-time, so it is not a check that the
465 -- compiler can suppress anyway, but we still have to recognize the check
466 -- name Allocation_Check since it is part of the standard.
468 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean is
469 begin
470 if Present (E) and then Checks_May_Be_Suppressed (E) then
471 return Is_Check_Suppressed (E, Allocation_Check);
472 else
473 return Scope_Suppress.Suppress (Allocation_Check);
474 end if;
475 end Allocation_Checks_Suppressed;
477 -------------------------
478 -- Append_Range_Checks --
479 -------------------------
481 procedure Append_Range_Checks
482 (Checks : Check_Result;
483 Stmts : List_Id;
484 Suppress_Typ : Entity_Id;
485 Static_Sloc : Source_Ptr;
486 Flag_Node : Node_Id)
488 Internal_Flag_Node : constant Node_Id := Flag_Node;
489 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
491 Checks_On : constant Boolean :=
492 (not Index_Checks_Suppressed (Suppress_Typ))
493 or else (not Range_Checks_Suppressed (Suppress_Typ));
495 begin
496 -- For now we just return if Checks_On is false, however this should
497 -- be enhanced to check for an always True value in the condition
498 -- and to generate a compilation warning???
500 if not Checks_On then
501 return;
502 end if;
504 for J in 1 .. 2 loop
505 exit when No (Checks (J));
507 if Nkind (Checks (J)) = N_Raise_Constraint_Error
508 and then Present (Condition (Checks (J)))
509 then
510 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
511 Append_To (Stmts, Checks (J));
512 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
513 end if;
515 else
516 Append_To
517 (Stmts,
518 Make_Raise_Constraint_Error (Internal_Static_Sloc,
519 Reason => CE_Range_Check_Failed));
520 end if;
521 end loop;
522 end Append_Range_Checks;
524 ------------------------
525 -- Apply_Access_Check --
526 ------------------------
528 procedure Apply_Access_Check (N : Node_Id) is
529 P : constant Node_Id := Prefix (N);
531 begin
532 -- We do not need checks if we are not generating code (i.e. the
533 -- expander is not active). This is not just an optimization, there
534 -- are cases (e.g. with pragma Debug) where generating the checks
535 -- can cause real trouble).
537 if not Expander_Active then
538 return;
539 end if;
541 -- No check if short circuiting makes check unnecessary
543 if not Check_Needed (P, Access_Check) then
544 return;
545 end if;
547 -- No check if accessing the Offset_To_Top component of a dispatch
548 -- table. They are safe by construction.
550 if Tagged_Type_Expansion
551 and then Present (Etype (P))
552 and then RTU_Loaded (Ada_Tags)
553 and then RTE_Available (RE_Offset_To_Top_Ptr)
554 and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
555 then
556 return;
557 end if;
559 -- Otherwise go ahead and install the check
561 Install_Null_Excluding_Check (P);
562 end Apply_Access_Check;
564 -------------------------------
565 -- Apply_Accessibility_Check --
566 -------------------------------
568 procedure Apply_Accessibility_Check
569 (N : Node_Id;
570 Typ : Entity_Id;
571 Insert_Node : Node_Id)
573 Loc : constant Source_Ptr := Sloc (N);
574 Param_Ent : Entity_Id := Param_Entity (N);
575 Param_Level : Node_Id;
576 Type_Level : Node_Id;
578 begin
579 if Ada_Version >= Ada_2012
580 and then not Present (Param_Ent)
581 and then Is_Entity_Name (N)
582 and then Ekind_In (Entity (N), E_Constant, E_Variable)
583 and then Present (Effective_Extra_Accessibility (Entity (N)))
584 then
585 Param_Ent := Entity (N);
586 while Present (Renamed_Object (Param_Ent)) loop
588 -- Renamed_Object must return an Entity_Name here
589 -- because of preceding "Present (E_E_A (...))" test.
591 Param_Ent := Entity (Renamed_Object (Param_Ent));
592 end loop;
593 end if;
595 if Inside_A_Generic then
596 return;
598 -- Only apply the run-time check if the access parameter has an
599 -- associated extra access level parameter and when the level of the
600 -- type is less deep than the level of the access parameter, and
601 -- accessibility checks are not suppressed.
603 elsif Present (Param_Ent)
604 and then Present (Extra_Accessibility (Param_Ent))
605 and then UI_Gt (Object_Access_Level (N),
606 Deepest_Type_Access_Level (Typ))
607 and then not Accessibility_Checks_Suppressed (Param_Ent)
608 and then not Accessibility_Checks_Suppressed (Typ)
609 then
610 Param_Level :=
611 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
613 Type_Level :=
614 Make_Integer_Literal (Loc, Deepest_Type_Access_Level (Typ));
616 -- Raise Program_Error if the accessibility level of the access
617 -- parameter is deeper than the level of the target access type.
619 Insert_Action (Insert_Node,
620 Make_Raise_Program_Error (Loc,
621 Condition =>
622 Make_Op_Gt (Loc,
623 Left_Opnd => Param_Level,
624 Right_Opnd => Type_Level),
625 Reason => PE_Accessibility_Check_Failed));
627 Analyze_And_Resolve (N);
628 end if;
629 end Apply_Accessibility_Check;
631 --------------------------------
632 -- Apply_Address_Clause_Check --
633 --------------------------------
635 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
636 pragma Assert (Nkind (N) = N_Freeze_Entity);
638 AC : constant Node_Id := Address_Clause (E);
639 Loc : constant Source_Ptr := Sloc (AC);
640 Typ : constant Entity_Id := Etype (E);
641 Aexp : constant Node_Id := Expression (AC);
643 Expr : Node_Id;
644 -- Address expression (not necessarily the same as Aexp, for example
645 -- when Aexp is a reference to a constant, in which case Expr gets
646 -- reset to reference the value expression of the constant).
648 procedure Compile_Time_Bad_Alignment;
649 -- Post error warnings when alignment is known to be incompatible. Note
650 -- that we do not go as far as inserting a raise of Program_Error since
651 -- this is an erroneous case, and it may happen that we are lucky and an
652 -- underaligned address turns out to be OK after all.
654 --------------------------------
655 -- Compile_Time_Bad_Alignment --
656 --------------------------------
658 procedure Compile_Time_Bad_Alignment is
659 begin
660 if Address_Clause_Overlay_Warnings then
661 Error_Msg_FE
662 ("?o?specified address for& may be inconsistent with alignment",
663 Aexp, E);
664 Error_Msg_FE
665 ("\?o?program execution may be erroneous (RM 13.3(27))",
666 Aexp, E);
667 Set_Address_Warning_Posted (AC);
668 end if;
669 end Compile_Time_Bad_Alignment;
671 -- Start of processing for Apply_Address_Clause_Check
673 begin
674 -- See if alignment check needed. Note that we never need a check if the
675 -- maximum alignment is one, since the check will always succeed.
677 -- Note: we do not check for checks suppressed here, since that check
678 -- was done in Sem_Ch13 when the address clause was processed. We are
679 -- only called if checks were not suppressed. The reason for this is
680 -- that we have to delay the call to Apply_Alignment_Check till freeze
681 -- time (so that all types etc are elaborated), but we have to check
682 -- the status of check suppressing at the point of the address clause.
684 if No (AC)
685 or else not Check_Address_Alignment (AC)
686 or else Maximum_Alignment = 1
687 then
688 return;
689 end if;
691 -- Obtain expression from address clause
693 Expr := Expression (AC);
695 -- The following loop digs for the real expression to use in the check
697 loop
698 -- For constant, get constant expression
700 if Is_Entity_Name (Expr)
701 and then Ekind (Entity (Expr)) = E_Constant
702 then
703 Expr := Constant_Value (Entity (Expr));
705 -- For unchecked conversion, get result to convert
707 elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
708 Expr := Expression (Expr);
710 -- For (common case) of To_Address call, get argument
712 elsif Nkind (Expr) = N_Function_Call
713 and then Is_Entity_Name (Name (Expr))
714 and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
715 then
716 Expr := First (Parameter_Associations (Expr));
718 if Nkind (Expr) = N_Parameter_Association then
719 Expr := Explicit_Actual_Parameter (Expr);
720 end if;
722 -- We finally have the real expression
724 else
725 exit;
726 end if;
727 end loop;
729 -- See if we know that Expr has a bad alignment at compile time
731 if Compile_Time_Known_Value (Expr)
732 and then (Known_Alignment (E) or else Known_Alignment (Typ))
733 then
734 declare
735 AL : Uint := Alignment (Typ);
737 begin
738 -- The object alignment might be more restrictive than the
739 -- type alignment.
741 if Known_Alignment (E) then
742 AL := Alignment (E);
743 end if;
745 if Expr_Value (Expr) mod AL /= 0 then
746 Compile_Time_Bad_Alignment;
747 else
748 return;
749 end if;
750 end;
752 -- If the expression has the form X'Address, then we can find out if
753 -- the object X has an alignment that is compatible with the object E.
754 -- If it hasn't or we don't know, we defer issuing the warning until
755 -- the end of the compilation to take into account back end annotations.
757 elsif Nkind (Expr) = N_Attribute_Reference
758 and then Attribute_Name (Expr) = Name_Address
759 and then Has_Compatible_Alignment (E, Prefix (Expr)) = Known_Compatible
760 then
761 return;
762 end if;
764 -- Here we do not know if the value is acceptable. Strictly we don't
765 -- have to do anything, since if the alignment is bad, we have an
766 -- erroneous program. However we are allowed to check for erroneous
767 -- conditions and we decide to do this by default if the check is not
768 -- suppressed.
770 -- However, don't do the check if elaboration code is unwanted
772 if Restriction_Active (No_Elaboration_Code) then
773 return;
775 -- Generate a check to raise PE if alignment may be inappropriate
777 else
778 -- If the original expression is a non-static constant, use the
779 -- name of the constant itself rather than duplicating its
780 -- defining expression, which was extracted above.
782 -- Note: Expr is empty if the address-clause is applied to in-mode
783 -- actuals (allowed by 13.1(22)).
785 if not Present (Expr)
786 or else
787 (Is_Entity_Name (Expression (AC))
788 and then Ekind (Entity (Expression (AC))) = E_Constant
789 and then Nkind (Parent (Entity (Expression (AC))))
790 = N_Object_Declaration)
791 then
792 Expr := New_Copy_Tree (Expression (AC));
793 else
794 Remove_Side_Effects (Expr);
795 end if;
797 if No (Actions (N)) then
798 Set_Actions (N, New_List);
799 end if;
801 Prepend_To (Actions (N),
802 Make_Raise_Program_Error (Loc,
803 Condition =>
804 Make_Op_Ne (Loc,
805 Left_Opnd =>
806 Make_Op_Mod (Loc,
807 Left_Opnd =>
808 Unchecked_Convert_To
809 (RTE (RE_Integer_Address), Expr),
810 Right_Opnd =>
811 Make_Attribute_Reference (Loc,
812 Prefix => New_Occurrence_Of (E, Loc),
813 Attribute_Name => Name_Alignment)),
814 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
815 Reason => PE_Misaligned_Address_Value));
817 Warning_Msg := No_Error_Msg;
818 Analyze (First (Actions (N)), Suppress => All_Checks);
820 -- If the address clause generated a warning message (for example,
821 -- from Warn_On_Non_Local_Exception mode with the active restriction
822 -- No_Exception_Propagation).
824 if Warning_Msg /= No_Error_Msg then
826 -- If the expression has a known at compile time value, then
827 -- once we know the alignment of the type, we can check if the
828 -- exception will be raised or not, and if not, we don't need
829 -- the warning so we will kill the warning later on.
831 if Compile_Time_Known_Value (Expr) then
832 Alignment_Warnings.Append
833 ((E => E, A => Expr_Value (Expr), W => Warning_Msg));
834 end if;
836 -- Add explanation of the warning that is generated by the check
838 Error_Msg_N
839 ("\address value may be incompatible with alignment "
840 & "of object?X?", AC);
841 end if;
843 return;
844 end if;
846 exception
847 -- If we have some missing run time component in configurable run time
848 -- mode then just skip the check (it is not required in any case).
850 when RE_Not_Available =>
851 return;
852 end Apply_Address_Clause_Check;
854 -------------------------------------
855 -- Apply_Arithmetic_Overflow_Check --
856 -------------------------------------
858 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
859 begin
860 -- Use old routine in almost all cases (the only case we are treating
861 -- specially is the case of a signed integer arithmetic op with the
862 -- overflow checking mode set to MINIMIZED or ELIMINATED).
864 if Overflow_Check_Mode = Strict
865 or else not Is_Signed_Integer_Arithmetic_Op (N)
866 then
867 Apply_Arithmetic_Overflow_Strict (N);
869 -- Otherwise use the new routine for the case of a signed integer
870 -- arithmetic op, with Do_Overflow_Check set to True, and the checking
871 -- mode is MINIMIZED or ELIMINATED.
873 else
874 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
875 end if;
876 end Apply_Arithmetic_Overflow_Check;
878 --------------------------------------
879 -- Apply_Arithmetic_Overflow_Strict --
880 --------------------------------------
882 -- This routine is called only if the type is an integer type, and a
883 -- software arithmetic overflow check may be needed for op (add, subtract,
884 -- or multiply). This check is performed only if Software_Overflow_Checking
885 -- is enabled and Do_Overflow_Check is set. In this case we expand the
886 -- operation into a more complex sequence of tests that ensures that
887 -- overflow is properly caught.
889 -- This is used in CHECKED modes. It is identical to the code for this
890 -- cases before the big overflow earthquake, thus ensuring that in this
891 -- modes we have compatible behavior (and reliability) to what was there
892 -- before. It is also called for types other than signed integers, and if
893 -- the Do_Overflow_Check flag is off.
895 -- Note: we also call this routine if we decide in the MINIMIZED case
896 -- to give up and just generate an overflow check without any fuss.
898 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id) is
899 Loc : constant Source_Ptr := Sloc (N);
900 Typ : constant Entity_Id := Etype (N);
901 Rtyp : constant Entity_Id := Root_Type (Typ);
903 begin
904 -- Nothing to do if Do_Overflow_Check not set or overflow checks
905 -- suppressed.
907 if not Do_Overflow_Check (N) then
908 return;
909 end if;
911 -- An interesting special case. If the arithmetic operation appears as
912 -- the operand of a type conversion:
914 -- type1 (x op y)
916 -- and all the following conditions apply:
918 -- arithmetic operation is for a signed integer type
919 -- target type type1 is a static integer subtype
920 -- range of x and y are both included in the range of type1
921 -- range of x op y is included in the range of type1
922 -- size of type1 is at least twice the result size of op
924 -- then we don't do an overflow check in any case, instead we transform
925 -- the operation so that we end up with:
927 -- type1 (type1 (x) op type1 (y))
929 -- This avoids intermediate overflow before the conversion. It is
930 -- explicitly permitted by RM 3.5.4(24):
932 -- For the execution of a predefined operation of a signed integer
933 -- type, the implementation need not raise Constraint_Error if the
934 -- result is outside the base range of the type, so long as the
935 -- correct result is produced.
937 -- It's hard to imagine that any programmer counts on the exception
938 -- being raised in this case, and in any case it's wrong coding to
939 -- have this expectation, given the RM permission. Furthermore, other
940 -- Ada compilers do allow such out of range results.
942 -- Note that we do this transformation even if overflow checking is
943 -- off, since this is precisely about giving the "right" result and
944 -- avoiding the need for an overflow check.
946 -- Note: this circuit is partially redundant with respect to the similar
947 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
948 -- with cases that do not come through here. We still need the following
949 -- processing even with the Exp_Ch4 code in place, since we want to be
950 -- sure not to generate the arithmetic overflow check in these cases
951 -- (Exp_Ch4 would have a hard time removing them once generated).
953 if Is_Signed_Integer_Type (Typ)
954 and then Nkind (Parent (N)) = N_Type_Conversion
955 then
956 Conversion_Optimization : declare
957 Target_Type : constant Entity_Id :=
958 Base_Type (Entity (Subtype_Mark (Parent (N))));
960 Llo, Lhi : Uint;
961 Rlo, Rhi : Uint;
962 LOK, ROK : Boolean;
964 Vlo : Uint;
965 Vhi : Uint;
966 VOK : Boolean;
968 Tlo : Uint;
969 Thi : Uint;
971 begin
972 if Is_Integer_Type (Target_Type)
973 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
974 then
975 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
976 Thi := Expr_Value (Type_High_Bound (Target_Type));
978 Determine_Range
979 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
980 Determine_Range
981 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
983 if (LOK and ROK)
984 and then Tlo <= Llo and then Lhi <= Thi
985 and then Tlo <= Rlo and then Rhi <= Thi
986 then
987 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
989 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
990 Rewrite (Left_Opnd (N),
991 Make_Type_Conversion (Loc,
992 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
993 Expression => Relocate_Node (Left_Opnd (N))));
995 Rewrite (Right_Opnd (N),
996 Make_Type_Conversion (Loc,
997 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
998 Expression => Relocate_Node (Right_Opnd (N))));
1000 -- Rewrite the conversion operand so that the original
1001 -- node is retained, in order to avoid the warning for
1002 -- redundant conversions in Resolve_Type_Conversion.
1004 Rewrite (N, Relocate_Node (N));
1006 Set_Etype (N, Target_Type);
1008 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
1009 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
1011 -- Given that the target type is twice the size of the
1012 -- source type, overflow is now impossible, so we can
1013 -- safely kill the overflow check and return.
1015 Set_Do_Overflow_Check (N, False);
1016 return;
1017 end if;
1018 end if;
1019 end if;
1020 end Conversion_Optimization;
1021 end if;
1023 -- Now see if an overflow check is required
1025 declare
1026 Siz : constant Int := UI_To_Int (Esize (Rtyp));
1027 Dsiz : constant Int := Siz * 2;
1028 Opnod : Node_Id;
1029 Ctyp : Entity_Id;
1030 Opnd : Node_Id;
1031 Cent : RE_Id;
1033 begin
1034 -- Skip check if back end does overflow checks, or the overflow flag
1035 -- is not set anyway, or we are not doing code expansion, or the
1036 -- parent node is a type conversion whose operand is an arithmetic
1037 -- operation on signed integers on which the expander can promote
1038 -- later the operands to type Integer (see Expand_N_Type_Conversion).
1040 -- Special case CLI target, where arithmetic overflow checks can be
1041 -- performed for integer and long_integer
1043 if Backend_Overflow_Checks_On_Target
1044 or else not Do_Overflow_Check (N)
1045 or else not Expander_Active
1046 or else (Present (Parent (N))
1047 and then Nkind (Parent (N)) = N_Type_Conversion
1048 and then Integer_Promotion_Possible (Parent (N)))
1049 or else
1050 (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
1051 then
1052 return;
1053 end if;
1055 -- Otherwise, generate the full general code for front end overflow
1056 -- detection, which works by doing arithmetic in a larger type:
1058 -- x op y
1060 -- is expanded into
1062 -- Typ (Checktyp (x) op Checktyp (y));
1064 -- where Typ is the type of the original expression, and Checktyp is
1065 -- an integer type of sufficient length to hold the largest possible
1066 -- result.
1068 -- If the size of check type exceeds the size of Long_Long_Integer,
1069 -- we use a different approach, expanding to:
1071 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
1073 -- where xxx is Add, Multiply or Subtract as appropriate
1075 -- Find check type if one exists
1077 if Dsiz <= Standard_Integer_Size then
1078 Ctyp := Standard_Integer;
1080 elsif Dsiz <= Standard_Long_Long_Integer_Size then
1081 Ctyp := Standard_Long_Long_Integer;
1083 -- No check type exists, use runtime call
1085 else
1086 if Nkind (N) = N_Op_Add then
1087 Cent := RE_Add_With_Ovflo_Check;
1089 elsif Nkind (N) = N_Op_Multiply then
1090 Cent := RE_Multiply_With_Ovflo_Check;
1092 else
1093 pragma Assert (Nkind (N) = N_Op_Subtract);
1094 Cent := RE_Subtract_With_Ovflo_Check;
1095 end if;
1097 Rewrite (N,
1098 OK_Convert_To (Typ,
1099 Make_Function_Call (Loc,
1100 Name => New_Occurrence_Of (RTE (Cent), Loc),
1101 Parameter_Associations => New_List (
1102 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
1103 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
1105 Analyze_And_Resolve (N, Typ);
1106 return;
1107 end if;
1109 -- If we fall through, we have the case where we do the arithmetic
1110 -- in the next higher type and get the check by conversion. In these
1111 -- cases Ctyp is set to the type to be used as the check type.
1113 Opnod := Relocate_Node (N);
1115 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
1117 Analyze (Opnd);
1118 Set_Etype (Opnd, Ctyp);
1119 Set_Analyzed (Opnd, True);
1120 Set_Left_Opnd (Opnod, Opnd);
1122 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
1124 Analyze (Opnd);
1125 Set_Etype (Opnd, Ctyp);
1126 Set_Analyzed (Opnd, True);
1127 Set_Right_Opnd (Opnod, Opnd);
1129 -- The type of the operation changes to the base type of the check
1130 -- type, and we reset the overflow check indication, since clearly no
1131 -- overflow is possible now that we are using a double length type.
1132 -- We also set the Analyzed flag to avoid a recursive attempt to
1133 -- expand the node.
1135 Set_Etype (Opnod, Base_Type (Ctyp));
1136 Set_Do_Overflow_Check (Opnod, False);
1137 Set_Analyzed (Opnod, True);
1139 -- Now build the outer conversion
1141 Opnd := OK_Convert_To (Typ, Opnod);
1142 Analyze (Opnd);
1143 Set_Etype (Opnd, Typ);
1145 -- In the discrete type case, we directly generate the range check
1146 -- for the outer operand. This range check will implement the
1147 -- required overflow check.
1149 if Is_Discrete_Type (Typ) then
1150 Rewrite (N, Opnd);
1151 Generate_Range_Check
1152 (Expression (N), Typ, CE_Overflow_Check_Failed);
1154 -- For other types, we enable overflow checking on the conversion,
1155 -- after setting the node as analyzed to prevent recursive attempts
1156 -- to expand the conversion node.
1158 else
1159 Set_Analyzed (Opnd, True);
1160 Enable_Overflow_Check (Opnd);
1161 Rewrite (N, Opnd);
1162 end if;
1164 exception
1165 when RE_Not_Available =>
1166 return;
1167 end;
1168 end Apply_Arithmetic_Overflow_Strict;
1170 ----------------------------------------------------
1171 -- Apply_Arithmetic_Overflow_Minimized_Eliminated --
1172 ----------------------------------------------------
1174 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id) is
1175 pragma Assert (Is_Signed_Integer_Arithmetic_Op (Op));
1177 Loc : constant Source_Ptr := Sloc (Op);
1178 P : constant Node_Id := Parent (Op);
1180 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
1181 -- Operands and results are of this type when we convert
1183 Result_Type : constant Entity_Id := Etype (Op);
1184 -- Original result type
1186 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1187 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
1189 Lo, Hi : Uint;
1190 -- Ranges of values for result
1192 begin
1193 -- Nothing to do if our parent is one of the following:
1195 -- Another signed integer arithmetic op
1196 -- A membership operation
1197 -- A comparison operation
1199 -- In all these cases, we will process at the higher level (and then
1200 -- this node will be processed during the downwards recursion that
1201 -- is part of the processing in Minimize_Eliminate_Overflows).
1203 if Is_Signed_Integer_Arithmetic_Op (P)
1204 or else Nkind (P) in N_Membership_Test
1205 or else Nkind (P) in N_Op_Compare
1207 -- This is also true for an alternative in a case expression
1209 or else Nkind (P) = N_Case_Expression_Alternative
1211 -- This is also true for a range operand in a membership test
1213 or else (Nkind (P) = N_Range
1214 and then Nkind (Parent (P)) in N_Membership_Test)
1215 then
1216 return;
1217 end if;
1219 -- Otherwise, we have a top level arithmetic operation node, and this
1220 -- is where we commence the special processing for MINIMIZED/ELIMINATED
1221 -- modes. This is the case where we tell the machinery not to move into
1222 -- Bignum mode at this top level (of course the top level operation
1223 -- will still be in Bignum mode if either of its operands are of type
1224 -- Bignum).
1226 Minimize_Eliminate_Overflows (Op, Lo, Hi, Top_Level => True);
1228 -- That call may but does not necessarily change the result type of Op.
1229 -- It is the job of this routine to undo such changes, so that at the
1230 -- top level, we have the proper type. This "undoing" is a point at
1231 -- which a final overflow check may be applied.
1233 -- If the result type was not fiddled we are all set. We go to base
1234 -- types here because things may have been rewritten to generate the
1235 -- base type of the operand types.
1237 if Base_Type (Etype (Op)) = Base_Type (Result_Type) then
1238 return;
1240 -- Bignum case
1242 elsif Is_RTE (Etype (Op), RE_Bignum) then
1244 -- We need a sequence that looks like:
1246 -- Rnn : Result_Type;
1248 -- declare
1249 -- M : Mark_Id := SS_Mark;
1250 -- begin
1251 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
1252 -- SS_Release (M);
1253 -- end;
1255 -- This block is inserted (using Insert_Actions), and then the node
1256 -- is replaced with a reference to Rnn.
1258 -- A special case arises if our parent is a conversion node. In this
1259 -- case no point in generating a conversion to Result_Type, we will
1260 -- let the parent handle this. Note that this special case is not
1261 -- just about optimization. Consider
1263 -- A,B,C : Integer;
1264 -- ...
1265 -- X := Long_Long_Integer'Base (A * (B ** C));
1267 -- Now the product may fit in Long_Long_Integer but not in Integer.
1268 -- In MINIMIZED/ELIMINATED mode, we don't want to introduce an
1269 -- overflow exception for this intermediate value.
1271 declare
1272 Blk : constant Node_Id := Make_Bignum_Block (Loc);
1273 Rnn : constant Entity_Id := Make_Temporary (Loc, 'R', Op);
1274 RHS : Node_Id;
1276 Rtype : Entity_Id;
1278 begin
1279 RHS := Convert_From_Bignum (Op);
1281 if Nkind (P) /= N_Type_Conversion then
1282 Convert_To_And_Rewrite (Result_Type, RHS);
1283 Rtype := Result_Type;
1285 -- Interesting question, do we need a check on that conversion
1286 -- operation. Answer, not if we know the result is in range.
1287 -- At the moment we are not taking advantage of this. To be
1288 -- looked at later ???
1290 else
1291 Rtype := LLIB;
1292 end if;
1294 Insert_Before
1295 (First (Statements (Handled_Statement_Sequence (Blk))),
1296 Make_Assignment_Statement (Loc,
1297 Name => New_Occurrence_Of (Rnn, Loc),
1298 Expression => RHS));
1300 Insert_Actions (Op, New_List (
1301 Make_Object_Declaration (Loc,
1302 Defining_Identifier => Rnn,
1303 Object_Definition => New_Occurrence_Of (Rtype, Loc)),
1304 Blk));
1306 Rewrite (Op, New_Occurrence_Of (Rnn, Loc));
1307 Analyze_And_Resolve (Op);
1308 end;
1310 -- Here we know the result is Long_Long_Integer'Base, of that it has
1311 -- been rewritten because the parent operation is a conversion. See
1312 -- Apply_Arithmetic_Overflow_Strict.Conversion_Optimization.
1314 else
1315 pragma Assert
1316 (Etype (Op) = LLIB or else Nkind (Parent (Op)) = N_Type_Conversion);
1318 -- All we need to do here is to convert the result to the proper
1319 -- result type. As explained above for the Bignum case, we can
1320 -- omit this if our parent is a type conversion.
1322 if Nkind (P) /= N_Type_Conversion then
1323 Convert_To_And_Rewrite (Result_Type, Op);
1324 end if;
1326 Analyze_And_Resolve (Op);
1327 end if;
1328 end Apply_Arithmetic_Overflow_Minimized_Eliminated;
1330 ----------------------------
1331 -- Apply_Constraint_Check --
1332 ----------------------------
1334 procedure Apply_Constraint_Check
1335 (N : Node_Id;
1336 Typ : Entity_Id;
1337 No_Sliding : Boolean := False)
1339 Desig_Typ : Entity_Id;
1341 begin
1342 -- No checks inside a generic (check the instantiations)
1344 if Inside_A_Generic then
1345 return;
1346 end if;
1348 -- Apply required constraint checks
1350 if Is_Scalar_Type (Typ) then
1351 Apply_Scalar_Range_Check (N, Typ);
1353 elsif Is_Array_Type (Typ) then
1355 -- A useful optimization: an aggregate with only an others clause
1356 -- always has the right bounds.
1358 if Nkind (N) = N_Aggregate
1359 and then No (Expressions (N))
1360 and then Nkind
1361 (First (Choices (First (Component_Associations (N)))))
1362 = N_Others_Choice
1363 then
1364 return;
1365 end if;
1367 if Is_Constrained (Typ) then
1368 Apply_Length_Check (N, Typ);
1370 if No_Sliding then
1371 Apply_Range_Check (N, Typ);
1372 end if;
1373 else
1374 Apply_Range_Check (N, Typ);
1375 end if;
1377 elsif (Is_Record_Type (Typ) or else Is_Private_Type (Typ))
1378 and then Has_Discriminants (Base_Type (Typ))
1379 and then Is_Constrained (Typ)
1380 then
1381 Apply_Discriminant_Check (N, Typ);
1383 elsif Is_Access_Type (Typ) then
1385 Desig_Typ := Designated_Type (Typ);
1387 -- No checks necessary if expression statically null
1389 if Known_Null (N) then
1390 if Can_Never_Be_Null (Typ) then
1391 Install_Null_Excluding_Check (N);
1392 end if;
1394 -- No sliding possible on access to arrays
1396 elsif Is_Array_Type (Desig_Typ) then
1397 if Is_Constrained (Desig_Typ) then
1398 Apply_Length_Check (N, Typ);
1399 end if;
1401 Apply_Range_Check (N, Typ);
1403 elsif Has_Discriminants (Base_Type (Desig_Typ))
1404 and then Is_Constrained (Desig_Typ)
1405 then
1406 Apply_Discriminant_Check (N, Typ);
1407 end if;
1409 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1410 -- this check if the constraint node is illegal, as shown by having
1411 -- an error posted. This additional guard prevents cascaded errors
1412 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1414 if Can_Never_Be_Null (Typ)
1415 and then not Can_Never_Be_Null (Etype (N))
1416 and then not Error_Posted (N)
1417 then
1418 Install_Null_Excluding_Check (N);
1419 end if;
1420 end if;
1421 end Apply_Constraint_Check;
1423 ------------------------------
1424 -- Apply_Discriminant_Check --
1425 ------------------------------
1427 procedure Apply_Discriminant_Check
1428 (N : Node_Id;
1429 Typ : Entity_Id;
1430 Lhs : Node_Id := Empty)
1432 Loc : constant Source_Ptr := Sloc (N);
1433 Do_Access : constant Boolean := Is_Access_Type (Typ);
1434 S_Typ : Entity_Id := Etype (N);
1435 Cond : Node_Id;
1436 T_Typ : Entity_Id;
1438 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1439 -- A heap object with an indefinite subtype is constrained by its
1440 -- initial value, and assigning to it requires a constraint_check.
1441 -- The target may be an explicit dereference, or a renaming of one.
1443 function Is_Aliased_Unconstrained_Component return Boolean;
1444 -- It is possible for an aliased component to have a nominal
1445 -- unconstrained subtype (through instantiation). If this is a
1446 -- discriminated component assigned in the expansion of an aggregate
1447 -- in an initialization, the check must be suppressed. This unusual
1448 -- situation requires a predicate of its own.
1450 ----------------------------------
1451 -- Denotes_Explicit_Dereference --
1452 ----------------------------------
1454 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1455 begin
1456 return
1457 Nkind (Obj) = N_Explicit_Dereference
1458 or else
1459 (Is_Entity_Name (Obj)
1460 and then Present (Renamed_Object (Entity (Obj)))
1461 and then Nkind (Renamed_Object (Entity (Obj))) =
1462 N_Explicit_Dereference);
1463 end Denotes_Explicit_Dereference;
1465 ----------------------------------------
1466 -- Is_Aliased_Unconstrained_Component --
1467 ----------------------------------------
1469 function Is_Aliased_Unconstrained_Component return Boolean is
1470 Comp : Entity_Id;
1471 Pref : Node_Id;
1473 begin
1474 if Nkind (Lhs) /= N_Selected_Component then
1475 return False;
1476 else
1477 Comp := Entity (Selector_Name (Lhs));
1478 Pref := Prefix (Lhs);
1479 end if;
1481 if Ekind (Comp) /= E_Component
1482 or else not Is_Aliased (Comp)
1483 then
1484 return False;
1485 end if;
1487 return not Comes_From_Source (Pref)
1488 and then In_Instance
1489 and then not Is_Constrained (Etype (Comp));
1490 end Is_Aliased_Unconstrained_Component;
1492 -- Start of processing for Apply_Discriminant_Check
1494 begin
1495 if Do_Access then
1496 T_Typ := Designated_Type (Typ);
1497 else
1498 T_Typ := Typ;
1499 end if;
1501 -- Nothing to do if discriminant checks are suppressed or else no code
1502 -- is to be generated
1504 if not Expander_Active
1505 or else Discriminant_Checks_Suppressed (T_Typ)
1506 then
1507 return;
1508 end if;
1510 -- No discriminant checks necessary for an access when expression is
1511 -- statically Null. This is not only an optimization, it is fundamental
1512 -- because otherwise discriminant checks may be generated in init procs
1513 -- for types containing an access to a not-yet-frozen record, causing a
1514 -- deadly forward reference.
1516 -- Also, if the expression is of an access type whose designated type is
1517 -- incomplete, then the access value must be null and we suppress the
1518 -- check.
1520 if Known_Null (N) then
1521 return;
1523 elsif Is_Access_Type (S_Typ) then
1524 S_Typ := Designated_Type (S_Typ);
1526 if Ekind (S_Typ) = E_Incomplete_Type then
1527 return;
1528 end if;
1529 end if;
1531 -- If an assignment target is present, then we need to generate the
1532 -- actual subtype if the target is a parameter or aliased object with
1533 -- an unconstrained nominal subtype.
1535 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1536 -- subtype to the parameter and dereference cases, since other aliased
1537 -- objects are unconstrained (unless the nominal subtype is explicitly
1538 -- constrained).
1540 if Present (Lhs)
1541 and then (Present (Param_Entity (Lhs))
1542 or else (Ada_Version < Ada_2005
1543 and then not Is_Constrained (T_Typ)
1544 and then Is_Aliased_View (Lhs)
1545 and then not Is_Aliased_Unconstrained_Component)
1546 or else (Ada_Version >= Ada_2005
1547 and then not Is_Constrained (T_Typ)
1548 and then Denotes_Explicit_Dereference (Lhs)
1549 and then Nkind (Original_Node (Lhs)) /=
1550 N_Function_Call))
1551 then
1552 T_Typ := Get_Actual_Subtype (Lhs);
1553 end if;
1555 -- Nothing to do if the type is unconstrained (this is the case where
1556 -- the actual subtype in the RM sense of N is unconstrained and no check
1557 -- is required).
1559 if not Is_Constrained (T_Typ) then
1560 return;
1562 -- Ada 2005: nothing to do if the type is one for which there is a
1563 -- partial view that is constrained.
1565 elsif Ada_Version >= Ada_2005
1566 and then Object_Type_Has_Constrained_Partial_View
1567 (Typ => Base_Type (T_Typ),
1568 Scop => Current_Scope)
1569 then
1570 return;
1571 end if;
1573 -- Nothing to do if the type is an Unchecked_Union
1575 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1576 return;
1577 end if;
1579 -- Suppress checks if the subtypes are the same. The check must be
1580 -- preserved in an assignment to a formal, because the constraint is
1581 -- given by the actual.
1583 if Nkind (Original_Node (N)) /= N_Allocator
1584 and then (No (Lhs)
1585 or else not Is_Entity_Name (Lhs)
1586 or else No (Param_Entity (Lhs)))
1587 then
1588 if (Etype (N) = Typ
1589 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1590 and then not Is_Aliased_View (Lhs)
1591 then
1592 return;
1593 end if;
1595 -- We can also eliminate checks on allocators with a subtype mark that
1596 -- coincides with the context type. The context type may be a subtype
1597 -- without a constraint (common case, a generic actual).
1599 elsif Nkind (Original_Node (N)) = N_Allocator
1600 and then Is_Entity_Name (Expression (Original_Node (N)))
1601 then
1602 declare
1603 Alloc_Typ : constant Entity_Id :=
1604 Entity (Expression (Original_Node (N)));
1606 begin
1607 if Alloc_Typ = T_Typ
1608 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1609 and then Is_Entity_Name (
1610 Subtype_Indication (Parent (T_Typ)))
1611 and then Alloc_Typ = Base_Type (T_Typ))
1613 then
1614 return;
1615 end if;
1616 end;
1617 end if;
1619 -- See if we have a case where the types are both constrained, and all
1620 -- the constraints are constants. In this case, we can do the check
1621 -- successfully at compile time.
1623 -- We skip this check for the case where the node is rewritten as
1624 -- an allocator, because it already carries the context subtype,
1625 -- and extracting the discriminants from the aggregate is messy.
1627 if Is_Constrained (S_Typ)
1628 and then Nkind (Original_Node (N)) /= N_Allocator
1629 then
1630 declare
1631 DconT : Elmt_Id;
1632 Discr : Entity_Id;
1633 DconS : Elmt_Id;
1634 ItemS : Node_Id;
1635 ItemT : Node_Id;
1637 begin
1638 -- S_Typ may not have discriminants in the case where it is a
1639 -- private type completed by a default discriminated type. In that
1640 -- case, we need to get the constraints from the underlying type.
1641 -- If the underlying type is unconstrained (i.e. has no default
1642 -- discriminants) no check is needed.
1644 if Has_Discriminants (S_Typ) then
1645 Discr := First_Discriminant (S_Typ);
1646 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1648 else
1649 Discr := First_Discriminant (Underlying_Type (S_Typ));
1650 DconS :=
1651 First_Elmt
1652 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1654 if No (DconS) then
1655 return;
1656 end if;
1658 -- A further optimization: if T_Typ is derived from S_Typ
1659 -- without imposing a constraint, no check is needed.
1661 if Nkind (Original_Node (Parent (T_Typ))) =
1662 N_Full_Type_Declaration
1663 then
1664 declare
1665 Type_Def : constant Node_Id :=
1666 Type_Definition (Original_Node (Parent (T_Typ)));
1667 begin
1668 if Nkind (Type_Def) = N_Derived_Type_Definition
1669 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1670 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1671 then
1672 return;
1673 end if;
1674 end;
1675 end if;
1676 end if;
1678 -- Constraint may appear in full view of type
1680 if Ekind (T_Typ) = E_Private_Subtype
1681 and then Present (Full_View (T_Typ))
1682 then
1683 DconT :=
1684 First_Elmt (Discriminant_Constraint (Full_View (T_Typ)));
1685 else
1686 DconT :=
1687 First_Elmt (Discriminant_Constraint (T_Typ));
1688 end if;
1690 while Present (Discr) loop
1691 ItemS := Node (DconS);
1692 ItemT := Node (DconT);
1694 -- For a discriminated component type constrained by the
1695 -- current instance of an enclosing type, there is no
1696 -- applicable discriminant check.
1698 if Nkind (ItemT) = N_Attribute_Reference
1699 and then Is_Access_Type (Etype (ItemT))
1700 and then Is_Entity_Name (Prefix (ItemT))
1701 and then Is_Type (Entity (Prefix (ItemT)))
1702 then
1703 return;
1704 end if;
1706 -- If the expressions for the discriminants are identical
1707 -- and it is side-effect free (for now just an entity),
1708 -- this may be a shared constraint, e.g. from a subtype
1709 -- without a constraint introduced as a generic actual.
1710 -- Examine other discriminants if any.
1712 if ItemS = ItemT
1713 and then Is_Entity_Name (ItemS)
1714 then
1715 null;
1717 elsif not Is_OK_Static_Expression (ItemS)
1718 or else not Is_OK_Static_Expression (ItemT)
1719 then
1720 exit;
1722 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1723 if Do_Access then -- needs run-time check.
1724 exit;
1725 else
1726 Apply_Compile_Time_Constraint_Error
1727 (N, "incorrect value for discriminant&??",
1728 CE_Discriminant_Check_Failed, Ent => Discr);
1729 return;
1730 end if;
1731 end if;
1733 Next_Elmt (DconS);
1734 Next_Elmt (DconT);
1735 Next_Discriminant (Discr);
1736 end loop;
1738 if No (Discr) then
1739 return;
1740 end if;
1741 end;
1742 end if;
1744 -- Here we need a discriminant check. First build the expression
1745 -- for the comparisons of the discriminants:
1747 -- (n.disc1 /= typ.disc1) or else
1748 -- (n.disc2 /= typ.disc2) or else
1749 -- ...
1750 -- (n.discn /= typ.discn)
1752 Cond := Build_Discriminant_Checks (N, T_Typ);
1754 -- If Lhs is set and is a parameter, then the condition is guarded by:
1755 -- lhs'constrained and then (condition built above)
1757 if Present (Param_Entity (Lhs)) then
1758 Cond :=
1759 Make_And_Then (Loc,
1760 Left_Opnd =>
1761 Make_Attribute_Reference (Loc,
1762 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1763 Attribute_Name => Name_Constrained),
1764 Right_Opnd => Cond);
1765 end if;
1767 if Do_Access then
1768 Cond := Guard_Access (Cond, Loc, N);
1769 end if;
1771 Insert_Action (N,
1772 Make_Raise_Constraint_Error (Loc,
1773 Condition => Cond,
1774 Reason => CE_Discriminant_Check_Failed));
1775 end Apply_Discriminant_Check;
1777 -------------------------
1778 -- Apply_Divide_Checks --
1779 -------------------------
1781 procedure Apply_Divide_Checks (N : Node_Id) is
1782 Loc : constant Source_Ptr := Sloc (N);
1783 Typ : constant Entity_Id := Etype (N);
1784 Left : constant Node_Id := Left_Opnd (N);
1785 Right : constant Node_Id := Right_Opnd (N);
1787 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1788 -- Current overflow checking mode
1790 LLB : Uint;
1791 Llo : Uint;
1792 Lhi : Uint;
1793 LOK : Boolean;
1794 Rlo : Uint;
1795 Rhi : Uint;
1796 ROK : Boolean;
1798 pragma Warnings (Off, Lhi);
1799 -- Don't actually use this value
1801 begin
1802 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1803 -- operating on signed integer types, then the only thing this routine
1804 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1805 -- procedure will (possibly later on during recursive downward calls),
1806 -- ensure that any needed overflow/division checks are properly applied.
1808 if Mode in Minimized_Or_Eliminated
1809 and then Is_Signed_Integer_Type (Typ)
1810 then
1811 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
1812 return;
1813 end if;
1815 -- Proceed here in SUPPRESSED or CHECKED modes
1817 if Expander_Active
1818 and then not Backend_Divide_Checks_On_Target
1819 and then Check_Needed (Right, Division_Check)
1820 then
1821 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1823 -- Deal with division check
1825 if Do_Division_Check (N)
1826 and then not Division_Checks_Suppressed (Typ)
1827 then
1828 Apply_Division_Check (N, Rlo, Rhi, ROK);
1829 end if;
1831 -- Deal with overflow check
1833 if Do_Overflow_Check (N)
1834 and then not Overflow_Checks_Suppressed (Etype (N))
1835 then
1836 Set_Do_Overflow_Check (N, False);
1838 -- Test for extremely annoying case of xxx'First divided by -1
1839 -- for division of signed integer types (only overflow case).
1841 if Nkind (N) = N_Op_Divide
1842 and then Is_Signed_Integer_Type (Typ)
1843 then
1844 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1845 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1847 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1848 and then
1849 ((not LOK) or else (Llo = LLB))
1850 then
1851 Insert_Action (N,
1852 Make_Raise_Constraint_Error (Loc,
1853 Condition =>
1854 Make_And_Then (Loc,
1855 Left_Opnd =>
1856 Make_Op_Eq (Loc,
1857 Left_Opnd =>
1858 Duplicate_Subexpr_Move_Checks (Left),
1859 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1861 Right_Opnd =>
1862 Make_Op_Eq (Loc,
1863 Left_Opnd => Duplicate_Subexpr (Right),
1864 Right_Opnd => Make_Integer_Literal (Loc, -1))),
1866 Reason => CE_Overflow_Check_Failed));
1867 end if;
1868 end if;
1869 end if;
1870 end if;
1871 end Apply_Divide_Checks;
1873 --------------------------
1874 -- Apply_Division_Check --
1875 --------------------------
1877 procedure Apply_Division_Check
1878 (N : Node_Id;
1879 Rlo : Uint;
1880 Rhi : Uint;
1881 ROK : Boolean)
1883 pragma Assert (Do_Division_Check (N));
1885 Loc : constant Source_Ptr := Sloc (N);
1886 Right : constant Node_Id := Right_Opnd (N);
1888 begin
1889 if Expander_Active
1890 and then not Backend_Divide_Checks_On_Target
1891 and then Check_Needed (Right, Division_Check)
1892 then
1893 -- See if division by zero possible, and if so generate test. This
1894 -- part of the test is not controlled by the -gnato switch, since
1895 -- it is a Division_Check and not an Overflow_Check.
1897 if Do_Division_Check (N) then
1898 Set_Do_Division_Check (N, False);
1900 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1901 Insert_Action (N,
1902 Make_Raise_Constraint_Error (Loc,
1903 Condition =>
1904 Make_Op_Eq (Loc,
1905 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1906 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1907 Reason => CE_Divide_By_Zero));
1908 end if;
1909 end if;
1910 end if;
1911 end Apply_Division_Check;
1913 ----------------------------------
1914 -- Apply_Float_Conversion_Check --
1915 ----------------------------------
1917 -- Let F and I be the source and target types of the conversion. The RM
1918 -- specifies that a floating-point value X is rounded to the nearest
1919 -- integer, with halfway cases being rounded away from zero. The rounded
1920 -- value of X is checked against I'Range.
1922 -- The catch in the above paragraph is that there is no good way to know
1923 -- whether the round-to-integer operation resulted in overflow. A remedy is
1924 -- to perform a range check in the floating-point domain instead, however:
1926 -- (1) The bounds may not be known at compile time
1927 -- (2) The check must take into account rounding or truncation.
1928 -- (3) The range of type I may not be exactly representable in F.
1929 -- (4) For the rounding case, The end-points I'First - 0.5 and
1930 -- I'Last + 0.5 may or may not be in range, depending on the
1931 -- sign of I'First and I'Last.
1932 -- (5) X may be a NaN, which will fail any comparison
1934 -- The following steps correctly convert X with rounding:
1936 -- (1) If either I'First or I'Last is not known at compile time, use
1937 -- I'Base instead of I in the next three steps and perform a
1938 -- regular range check against I'Range after conversion.
1939 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1940 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1941 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1942 -- In other words, take one of the closest floating-point numbers
1943 -- (which is an integer value) to I'First, and see if it is in
1944 -- range or not.
1945 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1946 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1947 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1948 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1949 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1951 -- For the truncating case, replace steps (2) and (3) as follows:
1952 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1953 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1954 -- Lo_OK be True.
1955 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1956 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1957 -- Hi_OK be True.
1959 procedure Apply_Float_Conversion_Check
1960 (Ck_Node : Node_Id;
1961 Target_Typ : Entity_Id)
1963 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1964 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1965 Loc : constant Source_Ptr := Sloc (Ck_Node);
1966 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1967 Target_Base : constant Entity_Id :=
1968 Implementation_Base_Type (Target_Typ);
1970 Par : constant Node_Id := Parent (Ck_Node);
1971 pragma Assert (Nkind (Par) = N_Type_Conversion);
1972 -- Parent of check node, must be a type conversion
1974 Truncate : constant Boolean := Float_Truncate (Par);
1975 Max_Bound : constant Uint :=
1976 UI_Expon
1977 (Machine_Radix_Value (Expr_Type),
1978 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
1980 -- Largest bound, so bound plus or minus half is a machine number of F
1982 Ifirst, Ilast : Uint;
1983 -- Bounds of integer type
1985 Lo, Hi : Ureal;
1986 -- Bounds to check in floating-point domain
1988 Lo_OK, Hi_OK : Boolean;
1989 -- True iff Lo resp. Hi belongs to I'Range
1991 Lo_Chk, Hi_Chk : Node_Id;
1992 -- Expressions that are False iff check fails
1994 Reason : RT_Exception_Code;
1996 begin
1997 -- We do not need checks if we are not generating code (i.e. the full
1998 -- expander is not active). In SPARK mode, we specifically don't want
1999 -- the frontend to expand these checks, which are dealt with directly
2000 -- in the formal verification backend.
2002 if not Expander_Active then
2003 return;
2004 end if;
2006 if not Compile_Time_Known_Value (LB)
2007 or not Compile_Time_Known_Value (HB)
2008 then
2009 declare
2010 -- First check that the value falls in the range of the base type,
2011 -- to prevent overflow during conversion and then perform a
2012 -- regular range check against the (dynamic) bounds.
2014 pragma Assert (Target_Base /= Target_Typ);
2016 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
2018 begin
2019 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
2020 Set_Etype (Temp, Target_Base);
2022 Insert_Action (Parent (Par),
2023 Make_Object_Declaration (Loc,
2024 Defining_Identifier => Temp,
2025 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
2026 Expression => New_Copy_Tree (Par)),
2027 Suppress => All_Checks);
2029 Insert_Action (Par,
2030 Make_Raise_Constraint_Error (Loc,
2031 Condition =>
2032 Make_Not_In (Loc,
2033 Left_Opnd => New_Occurrence_Of (Temp, Loc),
2034 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
2035 Reason => CE_Range_Check_Failed));
2036 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
2038 return;
2039 end;
2040 end if;
2042 -- Get the (static) bounds of the target type
2044 Ifirst := Expr_Value (LB);
2045 Ilast := Expr_Value (HB);
2047 -- A simple optimization: if the expression is a universal literal,
2048 -- we can do the comparison with the bounds and the conversion to
2049 -- an integer type statically. The range checks are unchanged.
2051 if Nkind (Ck_Node) = N_Real_Literal
2052 and then Etype (Ck_Node) = Universal_Real
2053 and then Is_Integer_Type (Target_Typ)
2054 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
2055 then
2056 declare
2057 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
2059 begin
2060 if Int_Val <= Ilast and then Int_Val >= Ifirst then
2062 -- Conversion is safe
2064 Rewrite (Parent (Ck_Node),
2065 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
2066 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
2067 return;
2068 end if;
2069 end;
2070 end if;
2072 -- Check against lower bound
2074 if Truncate and then Ifirst > 0 then
2075 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
2076 Lo_OK := False;
2078 elsif Truncate then
2079 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
2080 Lo_OK := True;
2082 elsif abs (Ifirst) < Max_Bound then
2083 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
2084 Lo_OK := (Ifirst > 0);
2086 else
2087 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
2088 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
2089 end if;
2091 if Lo_OK then
2093 -- Lo_Chk := (X >= Lo)
2095 Lo_Chk := Make_Op_Ge (Loc,
2096 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2097 Right_Opnd => Make_Real_Literal (Loc, Lo));
2099 else
2100 -- Lo_Chk := (X > Lo)
2102 Lo_Chk := Make_Op_Gt (Loc,
2103 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2104 Right_Opnd => Make_Real_Literal (Loc, Lo));
2105 end if;
2107 -- Check against higher bound
2109 if Truncate and then Ilast < 0 then
2110 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
2111 Hi_OK := False;
2113 elsif Truncate then
2114 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
2115 Hi_OK := True;
2117 elsif abs (Ilast) < Max_Bound then
2118 Hi := UR_From_Uint (Ilast) + Ureal_Half;
2119 Hi_OK := (Ilast < 0);
2120 else
2121 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
2122 Hi_OK := (Hi <= UR_From_Uint (Ilast));
2123 end if;
2125 if Hi_OK then
2127 -- Hi_Chk := (X <= Hi)
2129 Hi_Chk := Make_Op_Le (Loc,
2130 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2131 Right_Opnd => Make_Real_Literal (Loc, Hi));
2133 else
2134 -- Hi_Chk := (X < Hi)
2136 Hi_Chk := Make_Op_Lt (Loc,
2137 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2138 Right_Opnd => Make_Real_Literal (Loc, Hi));
2139 end if;
2141 -- If the bounds of the target type are the same as those of the base
2142 -- type, the check is an overflow check as a range check is not
2143 -- performed in these cases.
2145 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
2146 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
2147 then
2148 Reason := CE_Overflow_Check_Failed;
2149 else
2150 Reason := CE_Range_Check_Failed;
2151 end if;
2153 -- Raise CE if either conditions does not hold
2155 Insert_Action (Ck_Node,
2156 Make_Raise_Constraint_Error (Loc,
2157 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
2158 Reason => Reason));
2159 end Apply_Float_Conversion_Check;
2161 ------------------------
2162 -- Apply_Length_Check --
2163 ------------------------
2165 procedure Apply_Length_Check
2166 (Ck_Node : Node_Id;
2167 Target_Typ : Entity_Id;
2168 Source_Typ : Entity_Id := Empty)
2170 begin
2171 Apply_Selected_Length_Checks
2172 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2173 end Apply_Length_Check;
2175 -------------------------------------
2176 -- Apply_Parameter_Aliasing_Checks --
2177 -------------------------------------
2179 procedure Apply_Parameter_Aliasing_Checks
2180 (Call : Node_Id;
2181 Subp : Entity_Id)
2183 Loc : constant Source_Ptr := Sloc (Call);
2185 function May_Cause_Aliasing
2186 (Formal_1 : Entity_Id;
2187 Formal_2 : Entity_Id) return Boolean;
2188 -- Determine whether two formal parameters can alias each other
2189 -- depending on their modes.
2191 function Original_Actual (N : Node_Id) return Node_Id;
2192 -- The expander may replace an actual with a temporary for the sake of
2193 -- side effect removal. The temporary may hide a potential aliasing as
2194 -- it does not share the address of the actual. This routine attempts
2195 -- to retrieve the original actual.
2197 procedure Overlap_Check
2198 (Actual_1 : Node_Id;
2199 Actual_2 : Node_Id;
2200 Formal_1 : Entity_Id;
2201 Formal_2 : Entity_Id;
2202 Check : in out Node_Id);
2203 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2204 -- If detailed exception messages are enabled, the check is augmented to
2205 -- provide information about the names of the corresponding formals. See
2206 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2207 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2208 -- Check contains all and-ed simple tests generated so far or remains
2209 -- unchanged in the case of detailed exception messaged.
2211 ------------------------
2212 -- May_Cause_Aliasing --
2213 ------------------------
2215 function May_Cause_Aliasing
2216 (Formal_1 : Entity_Id;
2217 Formal_2 : Entity_Id) return Boolean
2219 begin
2220 -- The following combination cannot lead to aliasing
2222 -- Formal 1 Formal 2
2223 -- IN IN
2225 if Ekind (Formal_1) = E_In_Parameter
2226 and then
2227 Ekind (Formal_2) = E_In_Parameter
2228 then
2229 return False;
2231 -- The following combinations may lead to aliasing
2233 -- Formal 1 Formal 2
2234 -- IN OUT
2235 -- IN IN OUT
2236 -- OUT IN
2237 -- OUT IN OUT
2238 -- OUT OUT
2240 else
2241 return True;
2242 end if;
2243 end May_Cause_Aliasing;
2245 ---------------------
2246 -- Original_Actual --
2247 ---------------------
2249 function Original_Actual (N : Node_Id) return Node_Id is
2250 begin
2251 if Nkind (N) = N_Type_Conversion then
2252 return Expression (N);
2254 -- The expander created a temporary to capture the result of a type
2255 -- conversion where the expression is the real actual.
2257 elsif Nkind (N) = N_Identifier
2258 and then Present (Original_Node (N))
2259 and then Nkind (Original_Node (N)) = N_Type_Conversion
2260 then
2261 return Expression (Original_Node (N));
2262 end if;
2264 return N;
2265 end Original_Actual;
2267 -------------------
2268 -- Overlap_Check --
2269 -------------------
2271 procedure Overlap_Check
2272 (Actual_1 : Node_Id;
2273 Actual_2 : Node_Id;
2274 Formal_1 : Entity_Id;
2275 Formal_2 : Entity_Id;
2276 Check : in out Node_Id)
2278 Cond : Node_Id;
2279 ID_Casing : constant Casing_Type :=
2280 Identifier_Casing (Source_Index (Current_Sem_Unit));
2282 begin
2283 -- Generate:
2284 -- Actual_1'Overlaps_Storage (Actual_2)
2286 Cond :=
2287 Make_Attribute_Reference (Loc,
2288 Prefix => New_Copy_Tree (Original_Actual (Actual_1)),
2289 Attribute_Name => Name_Overlaps_Storage,
2290 Expressions =>
2291 New_List (New_Copy_Tree (Original_Actual (Actual_2))));
2293 -- Generate the following check when detailed exception messages are
2294 -- enabled:
2296 -- if Actual_1'Overlaps_Storage (Actual_2) then
2297 -- raise Program_Error with <detailed message>;
2298 -- end if;
2300 if Exception_Extra_Info then
2301 Start_String;
2303 -- Do not generate location information for internal calls
2305 if Comes_From_Source (Call) then
2306 Store_String_Chars (Build_Location_String (Loc));
2307 Store_String_Char (' ');
2308 end if;
2310 Store_String_Chars ("aliased parameters, actuals for """);
2312 Get_Name_String (Chars (Formal_1));
2313 Set_Casing (ID_Casing);
2314 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2316 Store_String_Chars (""" and """);
2318 Get_Name_String (Chars (Formal_2));
2319 Set_Casing (ID_Casing);
2320 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2322 Store_String_Chars (""" overlap");
2324 Insert_Action (Call,
2325 Make_If_Statement (Loc,
2326 Condition => Cond,
2327 Then_Statements => New_List (
2328 Make_Raise_Statement (Loc,
2329 Name =>
2330 New_Occurrence_Of (Standard_Program_Error, Loc),
2331 Expression => Make_String_Literal (Loc, End_String)))));
2333 -- Create a sequence of overlapping checks by and-ing them all
2334 -- together.
2336 else
2337 if No (Check) then
2338 Check := Cond;
2339 else
2340 Check :=
2341 Make_And_Then (Loc,
2342 Left_Opnd => Check,
2343 Right_Opnd => Cond);
2344 end if;
2345 end if;
2346 end Overlap_Check;
2348 -- Local variables
2350 Actual_1 : Node_Id;
2351 Actual_2 : Node_Id;
2352 Check : Node_Id;
2353 Formal_1 : Entity_Id;
2354 Formal_2 : Entity_Id;
2356 -- Start of processing for Apply_Parameter_Aliasing_Checks
2358 begin
2359 Check := Empty;
2361 Actual_1 := First_Actual (Call);
2362 Formal_1 := First_Formal (Subp);
2363 while Present (Actual_1) and then Present (Formal_1) loop
2365 -- Ensure that the actual is an object that is not passed by value.
2366 -- Elementary types are always passed by value, therefore actuals of
2367 -- such types cannot lead to aliasing.
2369 if Is_Object_Reference (Original_Actual (Actual_1))
2370 and then not Is_Elementary_Type (Etype (Original_Actual (Actual_1)))
2371 then
2372 Actual_2 := Next_Actual (Actual_1);
2373 Formal_2 := Next_Formal (Formal_1);
2374 while Present (Actual_2) and then Present (Formal_2) loop
2376 -- The other actual we are testing against must also denote
2377 -- a non pass-by-value object. Generate the check only when
2378 -- the mode of the two formals may lead to aliasing.
2380 if Is_Object_Reference (Original_Actual (Actual_2))
2381 and then not
2382 Is_Elementary_Type (Etype (Original_Actual (Actual_2)))
2383 and then May_Cause_Aliasing (Formal_1, Formal_2)
2384 then
2385 Overlap_Check
2386 (Actual_1 => Actual_1,
2387 Actual_2 => Actual_2,
2388 Formal_1 => Formal_1,
2389 Formal_2 => Formal_2,
2390 Check => Check);
2391 end if;
2393 Next_Actual (Actual_2);
2394 Next_Formal (Formal_2);
2395 end loop;
2396 end if;
2398 Next_Actual (Actual_1);
2399 Next_Formal (Formal_1);
2400 end loop;
2402 -- Place a simple check right before the call
2404 if Present (Check) and then not Exception_Extra_Info then
2405 Insert_Action (Call,
2406 Make_Raise_Program_Error (Loc,
2407 Condition => Check,
2408 Reason => PE_Aliased_Parameters));
2409 end if;
2410 end Apply_Parameter_Aliasing_Checks;
2412 -------------------------------------
2413 -- Apply_Parameter_Validity_Checks --
2414 -------------------------------------
2416 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id) is
2417 Subp_Decl : Node_Id;
2419 procedure Add_Validity_Check
2420 (Context : Entity_Id;
2421 PPC_Nam : Name_Id;
2422 For_Result : Boolean := False);
2423 -- Add a single 'Valid[_Scalar] check which verifies the initialization
2424 -- of Context. PPC_Nam denotes the pre or post condition pragma name.
2425 -- Set flag For_Result when to verify the result of a function.
2427 procedure Build_PPC_Pragma (PPC_Nam : Name_Id; Check : Node_Id);
2428 -- Create a pre or post condition pragma with name PPC_Nam which
2429 -- tests expression Check.
2431 ------------------------
2432 -- Add_Validity_Check --
2433 ------------------------
2435 procedure Add_Validity_Check
2436 (Context : Entity_Id;
2437 PPC_Nam : Name_Id;
2438 For_Result : Boolean := False)
2440 Loc : constant Source_Ptr := Sloc (Subp);
2441 Typ : constant Entity_Id := Etype (Context);
2442 Check : Node_Id;
2443 Nam : Name_Id;
2445 begin
2446 -- For scalars, generate 'Valid test
2448 if Is_Scalar_Type (Typ) then
2449 Nam := Name_Valid;
2451 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2453 elsif Scalar_Part_Present (Typ) then
2454 Nam := Name_Valid_Scalars;
2456 -- No test needed for other cases (no scalars to test)
2458 else
2459 return;
2460 end if;
2462 -- Step 1: Create the expression to verify the validity of the
2463 -- context.
2465 Check := New_Occurrence_Of (Context, Loc);
2467 -- When processing a function result, use 'Result. Generate
2468 -- Context'Result
2470 if For_Result then
2471 Check :=
2472 Make_Attribute_Reference (Loc,
2473 Prefix => Check,
2474 Attribute_Name => Name_Result);
2475 end if;
2477 -- Generate:
2478 -- Context['Result]'Valid[_Scalars]
2480 Check :=
2481 Make_Attribute_Reference (Loc,
2482 Prefix => Check,
2483 Attribute_Name => Nam);
2485 -- Step 2: Create a pre or post condition pragma
2487 Build_PPC_Pragma (PPC_Nam, Check);
2488 end Add_Validity_Check;
2490 ----------------------
2491 -- Build_PPC_Pragma --
2492 ----------------------
2494 procedure Build_PPC_Pragma (PPC_Nam : Name_Id; Check : Node_Id) is
2495 Loc : constant Source_Ptr := Sloc (Subp);
2496 Decls : List_Id;
2497 Prag : Node_Id;
2499 begin
2500 Prag :=
2501 Make_Pragma (Loc,
2502 Pragma_Identifier => Make_Identifier (Loc, PPC_Nam),
2503 Pragma_Argument_Associations => New_List (
2504 Make_Pragma_Argument_Association (Loc,
2505 Chars => Name_Check,
2506 Expression => Check)));
2508 -- Add a message unless exception messages are suppressed
2510 if not Exception_Locations_Suppressed then
2511 Append_To (Pragma_Argument_Associations (Prag),
2512 Make_Pragma_Argument_Association (Loc,
2513 Chars => Name_Message,
2514 Expression =>
2515 Make_String_Literal (Loc,
2516 Strval => "failed " & Get_Name_String (PPC_Nam) &
2517 " from " & Build_Location_String (Loc))));
2518 end if;
2520 -- Insert the pragma in the tree
2522 if Nkind (Parent (Subp_Decl)) = N_Compilation_Unit then
2523 Add_Global_Declaration (Prag);
2524 Analyze (Prag);
2526 -- PPC pragmas associated with subprogram bodies must be inserted in
2527 -- the declarative part of the body.
2529 elsif Nkind (Subp_Decl) = N_Subprogram_Body then
2530 Decls := Declarations (Subp_Decl);
2532 if No (Decls) then
2533 Decls := New_List;
2534 Set_Declarations (Subp_Decl, Decls);
2535 end if;
2537 Prepend_To (Decls, Prag);
2539 -- Ensure the proper visibility of the subprogram body and its
2540 -- parameters.
2542 Push_Scope (Subp);
2543 Analyze (Prag);
2544 Pop_Scope;
2546 -- For subprogram declarations insert the PPC pragma right after the
2547 -- declarative node.
2549 else
2550 Insert_After_And_Analyze (Subp_Decl, Prag);
2551 end if;
2552 end Build_PPC_Pragma;
2554 -- Local variables
2556 Formal : Entity_Id;
2557 Subp_Spec : Node_Id;
2559 -- Start of processing for Apply_Parameter_Validity_Checks
2561 begin
2562 -- Extract the subprogram specification and declaration nodes
2564 Subp_Spec := Parent (Subp);
2566 if Nkind (Subp_Spec) = N_Defining_Program_Unit_Name then
2567 Subp_Spec := Parent (Subp_Spec);
2568 end if;
2570 Subp_Decl := Parent (Subp_Spec);
2572 if not Comes_From_Source (Subp)
2574 -- Do not process formal subprograms because the corresponding actual
2575 -- will receive the proper checks when the instance is analyzed.
2577 or else Is_Formal_Subprogram (Subp)
2579 -- Do not process imported subprograms since pre and post conditions
2580 -- are never verified on routines coming from a different language.
2582 or else Is_Imported (Subp)
2583 or else Is_Intrinsic_Subprogram (Subp)
2585 -- The PPC pragmas generated by this routine do not correspond to
2586 -- source aspects, therefore they cannot be applied to abstract
2587 -- subprograms.
2589 or else Nkind (Subp_Decl) = N_Abstract_Subprogram_Declaration
2591 -- Do not consider subprogram renaminds because the renamed entity
2592 -- already has the proper PPC pragmas.
2594 or else Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
2596 -- Do not process null procedures because there is no benefit of
2597 -- adding the checks to a no action routine.
2599 or else (Nkind (Subp_Spec) = N_Procedure_Specification
2600 and then Null_Present (Subp_Spec))
2601 then
2602 return;
2603 end if;
2605 -- Inspect all the formals applying aliasing and scalar initialization
2606 -- checks where applicable.
2608 Formal := First_Formal (Subp);
2609 while Present (Formal) loop
2611 -- Generate the following scalar initialization checks for each
2612 -- formal parameter:
2614 -- mode IN - Pre => Formal'Valid[_Scalars]
2615 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2616 -- mode OUT - Post => Formal'Valid[_Scalars]
2618 if Check_Validity_Of_Parameters then
2619 if Ekind_In (Formal, E_In_Parameter, E_In_Out_Parameter) then
2620 Add_Validity_Check (Formal, Name_Precondition, False);
2621 end if;
2623 if Ekind_In (Formal, E_In_Out_Parameter, E_Out_Parameter) then
2624 Add_Validity_Check (Formal, Name_Postcondition, False);
2625 end if;
2626 end if;
2628 Next_Formal (Formal);
2629 end loop;
2631 -- Generate following scalar initialization check for function result:
2633 -- Post => Subp'Result'Valid[_Scalars]
2635 if Check_Validity_Of_Parameters and then Ekind (Subp) = E_Function then
2636 Add_Validity_Check (Subp, Name_Postcondition, True);
2637 end if;
2638 end Apply_Parameter_Validity_Checks;
2640 ---------------------------
2641 -- Apply_Predicate_Check --
2642 ---------------------------
2644 procedure Apply_Predicate_Check (N : Node_Id; Typ : Entity_Id) is
2645 S : Entity_Id;
2647 begin
2648 if Present (Predicate_Function (Typ)) then
2650 S := Current_Scope;
2651 while Present (S) and then not Is_Subprogram (S) loop
2652 S := Scope (S);
2653 end loop;
2655 -- A predicate check does not apply within internally generated
2656 -- subprograms, such as TSS functions.
2658 if Within_Internal_Subprogram then
2659 return;
2661 -- If the check appears within the predicate function itself, it
2662 -- means that the user specified a check whose formal is the
2663 -- predicated subtype itself, rather than some covering type. This
2664 -- is likely to be a common error, and thus deserves a warning.
2666 elsif Present (S) and then S = Predicate_Function (Typ) then
2667 Error_Msg_N
2668 ("predicate check includes a function call that "
2669 & "requires a predicate check??", Parent (N));
2670 Error_Msg_N
2671 ("\this will result in infinite recursion??", Parent (N));
2672 Insert_Action (N,
2673 Make_Raise_Storage_Error (Sloc (N),
2674 Reason => SE_Infinite_Recursion));
2676 -- Here for normal case of predicate active
2678 else
2679 -- If the type has a static predicate and the expression is known
2680 -- at compile time, see if the expression satisfies the predicate.
2682 Check_Expression_Against_Static_Predicate (N, Typ);
2684 Insert_Action (N,
2685 Make_Predicate_Check (Typ, Duplicate_Subexpr (N)));
2686 end if;
2687 end if;
2688 end Apply_Predicate_Check;
2690 -----------------------
2691 -- Apply_Range_Check --
2692 -----------------------
2694 procedure Apply_Range_Check
2695 (Ck_Node : Node_Id;
2696 Target_Typ : Entity_Id;
2697 Source_Typ : Entity_Id := Empty)
2699 begin
2700 Apply_Selected_Range_Checks
2701 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2702 end Apply_Range_Check;
2704 ------------------------------
2705 -- Apply_Scalar_Range_Check --
2706 ------------------------------
2708 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
2709 -- off if it is already set on.
2711 procedure Apply_Scalar_Range_Check
2712 (Expr : Node_Id;
2713 Target_Typ : Entity_Id;
2714 Source_Typ : Entity_Id := Empty;
2715 Fixed_Int : Boolean := False)
2717 Parnt : constant Node_Id := Parent (Expr);
2718 S_Typ : Entity_Id;
2719 Arr : Node_Id := Empty; -- initialize to prevent warning
2720 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
2721 OK : Boolean;
2723 Is_Subscr_Ref : Boolean;
2724 -- Set true if Expr is a subscript
2726 Is_Unconstrained_Subscr_Ref : Boolean;
2727 -- Set true if Expr is a subscript of an unconstrained array. In this
2728 -- case we do not attempt to do an analysis of the value against the
2729 -- range of the subscript, since we don't know the actual subtype.
2731 Int_Real : Boolean;
2732 -- Set to True if Expr should be regarded as a real value even though
2733 -- the type of Expr might be discrete.
2735 procedure Bad_Value;
2736 -- Procedure called if value is determined to be out of range
2738 ---------------
2739 -- Bad_Value --
2740 ---------------
2742 procedure Bad_Value is
2743 begin
2744 Apply_Compile_Time_Constraint_Error
2745 (Expr, "value not in range of}??", CE_Range_Check_Failed,
2746 Ent => Target_Typ,
2747 Typ => Target_Typ);
2748 end Bad_Value;
2750 -- Start of processing for Apply_Scalar_Range_Check
2752 begin
2753 -- Return if check obviously not needed
2756 -- Not needed inside generic
2758 Inside_A_Generic
2760 -- Not needed if previous error
2762 or else Target_Typ = Any_Type
2763 or else Nkind (Expr) = N_Error
2765 -- Not needed for non-scalar type
2767 or else not Is_Scalar_Type (Target_Typ)
2769 -- Not needed if we know node raises CE already
2771 or else Raises_Constraint_Error (Expr)
2772 then
2773 return;
2774 end if;
2776 -- Now, see if checks are suppressed
2778 Is_Subscr_Ref :=
2779 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
2781 if Is_Subscr_Ref then
2782 Arr := Prefix (Parnt);
2783 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
2785 if Is_Access_Type (Arr_Typ) then
2786 Arr_Typ := Designated_Type (Arr_Typ);
2787 end if;
2788 end if;
2790 if not Do_Range_Check (Expr) then
2792 -- Subscript reference. Check for Index_Checks suppressed
2794 if Is_Subscr_Ref then
2796 -- Check array type and its base type
2798 if Index_Checks_Suppressed (Arr_Typ)
2799 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
2800 then
2801 return;
2803 -- Check array itself if it is an entity name
2805 elsif Is_Entity_Name (Arr)
2806 and then Index_Checks_Suppressed (Entity (Arr))
2807 then
2808 return;
2810 -- Check expression itself if it is an entity name
2812 elsif Is_Entity_Name (Expr)
2813 and then Index_Checks_Suppressed (Entity (Expr))
2814 then
2815 return;
2816 end if;
2818 -- All other cases, check for Range_Checks suppressed
2820 else
2821 -- Check target type and its base type
2823 if Range_Checks_Suppressed (Target_Typ)
2824 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
2825 then
2826 return;
2828 -- Check expression itself if it is an entity name
2830 elsif Is_Entity_Name (Expr)
2831 and then Range_Checks_Suppressed (Entity (Expr))
2832 then
2833 return;
2835 -- If Expr is part of an assignment statement, then check left
2836 -- side of assignment if it is an entity name.
2838 elsif Nkind (Parnt) = N_Assignment_Statement
2839 and then Is_Entity_Name (Name (Parnt))
2840 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
2841 then
2842 return;
2843 end if;
2844 end if;
2845 end if;
2847 -- Do not set range checks if they are killed
2849 if Nkind (Expr) = N_Unchecked_Type_Conversion
2850 and then Kill_Range_Check (Expr)
2851 then
2852 return;
2853 end if;
2855 -- Do not set range checks for any values from System.Scalar_Values
2856 -- since the whole idea of such values is to avoid checking them.
2858 if Is_Entity_Name (Expr)
2859 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
2860 then
2861 return;
2862 end if;
2864 -- Now see if we need a check
2866 if No (Source_Typ) then
2867 S_Typ := Etype (Expr);
2868 else
2869 S_Typ := Source_Typ;
2870 end if;
2872 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
2873 return;
2874 end if;
2876 Is_Unconstrained_Subscr_Ref :=
2877 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
2879 -- Special checks for floating-point type
2881 if Is_Floating_Point_Type (S_Typ) then
2883 -- Always do a range check if the source type includes infinities and
2884 -- the target type does not include infinities. We do not do this if
2885 -- range checks are killed.
2887 if Has_Infinities (S_Typ)
2888 and then not Has_Infinities (Target_Typ)
2889 then
2890 Enable_Range_Check (Expr);
2891 end if;
2892 end if;
2894 -- Return if we know expression is definitely in the range of the target
2895 -- type as determined by Determine_Range. Right now we only do this for
2896 -- discrete types, and not fixed-point or floating-point types.
2898 -- The additional less-precise tests below catch these cases
2900 -- Note: skip this if we are given a source_typ, since the point of
2901 -- supplying a Source_Typ is to stop us looking at the expression.
2902 -- We could sharpen this test to be out parameters only ???
2904 if Is_Discrete_Type (Target_Typ)
2905 and then Is_Discrete_Type (Etype (Expr))
2906 and then not Is_Unconstrained_Subscr_Ref
2907 and then No (Source_Typ)
2908 then
2909 declare
2910 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
2911 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
2912 Lo : Uint;
2913 Hi : Uint;
2915 begin
2916 if Compile_Time_Known_Value (Tlo)
2917 and then Compile_Time_Known_Value (Thi)
2918 then
2919 declare
2920 Lov : constant Uint := Expr_Value (Tlo);
2921 Hiv : constant Uint := Expr_Value (Thi);
2923 begin
2924 -- If range is null, we for sure have a constraint error
2925 -- (we don't even need to look at the value involved,
2926 -- since all possible values will raise CE).
2928 if Lov > Hiv then
2929 Bad_Value;
2930 return;
2931 end if;
2933 -- Otherwise determine range of value
2935 Determine_Range (Expr, OK, Lo, Hi, Assume_Valid => True);
2937 if OK then
2939 -- If definitely in range, all OK
2941 if Lo >= Lov and then Hi <= Hiv then
2942 return;
2944 -- If definitely not in range, warn
2946 elsif Lov > Hi or else Hiv < Lo then
2947 Bad_Value;
2948 return;
2950 -- Otherwise we don't know
2952 else
2953 null;
2954 end if;
2955 end if;
2956 end;
2957 end if;
2958 end;
2959 end if;
2961 Int_Real :=
2962 Is_Floating_Point_Type (S_Typ)
2963 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
2965 -- Check if we can determine at compile time whether Expr is in the
2966 -- range of the target type. Note that if S_Typ is within the bounds
2967 -- of Target_Typ then this must be the case. This check is meaningful
2968 -- only if this is not a conversion between integer and real types.
2970 if not Is_Unconstrained_Subscr_Ref
2971 and then Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
2972 and then
2973 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
2975 -- Also check if the expression itself is in the range of the
2976 -- target type if it is a known at compile time value. We skip
2977 -- this test if S_Typ is set since for OUT and IN OUT parameters
2978 -- the Expr itself is not relevant to the checking.
2980 or else
2981 (No (Source_Typ)
2982 and then Is_In_Range (Expr, Target_Typ,
2983 Assume_Valid => True,
2984 Fixed_Int => Fixed_Int,
2985 Int_Real => Int_Real)))
2986 then
2987 return;
2989 elsif Is_Out_Of_Range (Expr, Target_Typ,
2990 Assume_Valid => True,
2991 Fixed_Int => Fixed_Int,
2992 Int_Real => Int_Real)
2993 then
2994 Bad_Value;
2995 return;
2997 -- Floating-point case
2998 -- In the floating-point case, we only do range checks if the type is
2999 -- constrained. We definitely do NOT want range checks for unconstrained
3000 -- types, since we want to have infinities
3002 elsif Is_Floating_Point_Type (S_Typ) then
3004 -- Normally, we only do range checks if the type is constrained. We do
3005 -- NOT want range checks for unconstrained types, since we want to have
3006 -- infinities.
3008 if Is_Constrained (S_Typ) then
3009 Enable_Range_Check (Expr);
3010 end if;
3012 -- For all other cases we enable a range check unconditionally
3014 else
3015 Enable_Range_Check (Expr);
3016 return;
3017 end if;
3018 end Apply_Scalar_Range_Check;
3020 ----------------------------------
3021 -- Apply_Selected_Length_Checks --
3022 ----------------------------------
3024 procedure Apply_Selected_Length_Checks
3025 (Ck_Node : Node_Id;
3026 Target_Typ : Entity_Id;
3027 Source_Typ : Entity_Id;
3028 Do_Static : Boolean)
3030 Cond : Node_Id;
3031 R_Result : Check_Result;
3032 R_Cno : Node_Id;
3034 Loc : constant Source_Ptr := Sloc (Ck_Node);
3035 Checks_On : constant Boolean :=
3036 (not Index_Checks_Suppressed (Target_Typ))
3037 or else (not Length_Checks_Suppressed (Target_Typ));
3039 begin
3040 -- Note: this means that we lose some useful warnings if the expander
3041 -- is not active, and we also lose these warnings in SPARK mode ???
3043 if not Expander_Active then
3044 return;
3045 end if;
3047 R_Result :=
3048 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3050 for J in 1 .. 2 loop
3051 R_Cno := R_Result (J);
3052 exit when No (R_Cno);
3054 -- A length check may mention an Itype which is attached to a
3055 -- subsequent node. At the top level in a package this can cause
3056 -- an order-of-elaboration problem, so we make sure that the itype
3057 -- is referenced now.
3059 if Ekind (Current_Scope) = E_Package
3060 and then Is_Compilation_Unit (Current_Scope)
3061 then
3062 Ensure_Defined (Target_Typ, Ck_Node);
3064 if Present (Source_Typ) then
3065 Ensure_Defined (Source_Typ, Ck_Node);
3067 elsif Is_Itype (Etype (Ck_Node)) then
3068 Ensure_Defined (Etype (Ck_Node), Ck_Node);
3069 end if;
3070 end if;
3072 -- If the item is a conditional raise of constraint error, then have
3073 -- a look at what check is being performed and ???
3075 if Nkind (R_Cno) = N_Raise_Constraint_Error
3076 and then Present (Condition (R_Cno))
3077 then
3078 Cond := Condition (R_Cno);
3080 -- Case where node does not now have a dynamic check
3082 if not Has_Dynamic_Length_Check (Ck_Node) then
3084 -- If checks are on, just insert the check
3086 if Checks_On then
3087 Insert_Action (Ck_Node, R_Cno);
3089 if not Do_Static then
3090 Set_Has_Dynamic_Length_Check (Ck_Node);
3091 end if;
3093 -- If checks are off, then analyze the length check after
3094 -- temporarily attaching it to the tree in case the relevant
3095 -- condition can be evaluated at compile time. We still want a
3096 -- compile time warning in this case.
3098 else
3099 Set_Parent (R_Cno, Ck_Node);
3100 Analyze (R_Cno);
3101 end if;
3102 end if;
3104 -- Output a warning if the condition is known to be True
3106 if Is_Entity_Name (Cond)
3107 and then Entity (Cond) = Standard_True
3108 then
3109 Apply_Compile_Time_Constraint_Error
3110 (Ck_Node, "wrong length for array of}??",
3111 CE_Length_Check_Failed,
3112 Ent => Target_Typ,
3113 Typ => Target_Typ);
3115 -- If we were only doing a static check, or if checks are not
3116 -- on, then we want to delete the check, since it is not needed.
3117 -- We do this by replacing the if statement by a null statement
3119 elsif Do_Static or else not Checks_On then
3120 Remove_Warning_Messages (R_Cno);
3121 Rewrite (R_Cno, Make_Null_Statement (Loc));
3122 end if;
3124 else
3125 Install_Static_Check (R_Cno, Loc);
3126 end if;
3127 end loop;
3128 end Apply_Selected_Length_Checks;
3130 ---------------------------------
3131 -- Apply_Selected_Range_Checks --
3132 ---------------------------------
3134 procedure Apply_Selected_Range_Checks
3135 (Ck_Node : Node_Id;
3136 Target_Typ : Entity_Id;
3137 Source_Typ : Entity_Id;
3138 Do_Static : Boolean)
3140 Loc : constant Source_Ptr := Sloc (Ck_Node);
3141 Checks_On : constant Boolean :=
3142 not Index_Checks_Suppressed (Target_Typ)
3143 or else
3144 not Range_Checks_Suppressed (Target_Typ);
3146 Cond : Node_Id;
3147 R_Cno : Node_Id;
3148 R_Result : Check_Result;
3150 begin
3151 if not Expander_Active or not Checks_On then
3152 return;
3153 end if;
3155 R_Result :=
3156 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3158 for J in 1 .. 2 loop
3159 R_Cno := R_Result (J);
3160 exit when No (R_Cno);
3162 -- The range check requires runtime evaluation. Depending on what its
3163 -- triggering condition is, the check may be converted into a compile
3164 -- time constraint check.
3166 if Nkind (R_Cno) = N_Raise_Constraint_Error
3167 and then Present (Condition (R_Cno))
3168 then
3169 Cond := Condition (R_Cno);
3171 -- Insert the range check before the related context. Note that
3172 -- this action analyses the triggering condition.
3174 Insert_Action (Ck_Node, R_Cno);
3176 -- This old code doesn't make sense, why is the context flagged as
3177 -- requiring dynamic range checks now in the middle of generating
3178 -- them ???
3180 if not Do_Static then
3181 Set_Has_Dynamic_Range_Check (Ck_Node);
3182 end if;
3184 -- The triggering condition evaluates to True, the range check
3185 -- can be converted into a compile time constraint check.
3187 if Is_Entity_Name (Cond)
3188 and then Entity (Cond) = Standard_True
3189 then
3190 -- Since an N_Range is technically not an expression, we have
3191 -- to set one of the bounds to C_E and then just flag the
3192 -- N_Range. The warning message will point to the lower bound
3193 -- and complain about a range, which seems OK.
3195 if Nkind (Ck_Node) = N_Range then
3196 Apply_Compile_Time_Constraint_Error
3197 (Low_Bound (Ck_Node),
3198 "static range out of bounds of}??",
3199 CE_Range_Check_Failed,
3200 Ent => Target_Typ,
3201 Typ => Target_Typ);
3203 Set_Raises_Constraint_Error (Ck_Node);
3205 else
3206 Apply_Compile_Time_Constraint_Error
3207 (Ck_Node,
3208 "static value out of range of}??",
3209 CE_Range_Check_Failed,
3210 Ent => Target_Typ,
3211 Typ => Target_Typ);
3212 end if;
3214 -- If we were only doing a static check, or if checks are not
3215 -- on, then we want to delete the check, since it is not needed.
3216 -- We do this by replacing the if statement by a null statement
3218 -- Why are we even generating checks if checks are turned off ???
3220 elsif Do_Static or else not Checks_On then
3221 Remove_Warning_Messages (R_Cno);
3222 Rewrite (R_Cno, Make_Null_Statement (Loc));
3223 end if;
3225 -- The range check raises Constrant_Error explicitly
3227 else
3228 Install_Static_Check (R_Cno, Loc);
3229 end if;
3230 end loop;
3231 end Apply_Selected_Range_Checks;
3233 -------------------------------
3234 -- Apply_Static_Length_Check --
3235 -------------------------------
3237 procedure Apply_Static_Length_Check
3238 (Expr : Node_Id;
3239 Target_Typ : Entity_Id;
3240 Source_Typ : Entity_Id := Empty)
3242 begin
3243 Apply_Selected_Length_Checks
3244 (Expr, Target_Typ, Source_Typ, Do_Static => True);
3245 end Apply_Static_Length_Check;
3247 -------------------------------------
3248 -- Apply_Subscript_Validity_Checks --
3249 -------------------------------------
3251 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
3252 Sub : Node_Id;
3254 begin
3255 pragma Assert (Nkind (Expr) = N_Indexed_Component);
3257 -- Loop through subscripts
3259 Sub := First (Expressions (Expr));
3260 while Present (Sub) loop
3262 -- Check one subscript. Note that we do not worry about enumeration
3263 -- type with holes, since we will convert the value to a Pos value
3264 -- for the subscript, and that convert will do the necessary validity
3265 -- check.
3267 Ensure_Valid (Sub, Holes_OK => True);
3269 -- Move to next subscript
3271 Sub := Next (Sub);
3272 end loop;
3273 end Apply_Subscript_Validity_Checks;
3275 ----------------------------------
3276 -- Apply_Type_Conversion_Checks --
3277 ----------------------------------
3279 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
3280 Target_Type : constant Entity_Id := Etype (N);
3281 Target_Base : constant Entity_Id := Base_Type (Target_Type);
3282 Expr : constant Node_Id := Expression (N);
3284 Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
3285 -- Note: if Etype (Expr) is a private type without discriminants, its
3286 -- full view might have discriminants with defaults, so we need the
3287 -- full view here to retrieve the constraints.
3289 begin
3290 if Inside_A_Generic then
3291 return;
3293 -- Skip these checks if serious errors detected, there are some nasty
3294 -- situations of incomplete trees that blow things up.
3296 elsif Serious_Errors_Detected > 0 then
3297 return;
3299 -- Never generate discriminant checks for Unchecked_Union types
3301 elsif Present (Expr_Type)
3302 and then Is_Unchecked_Union (Expr_Type)
3303 then
3304 return;
3306 -- Scalar type conversions of the form Target_Type (Expr) require a
3307 -- range check if we cannot be sure that Expr is in the base type of
3308 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3309 -- are not quite the same condition from an implementation point of
3310 -- view, but clearly the second includes the first.
3312 elsif Is_Scalar_Type (Target_Type) then
3313 declare
3314 Conv_OK : constant Boolean := Conversion_OK (N);
3315 -- If the Conversion_OK flag on the type conversion is set and no
3316 -- floating-point type is involved in the type conversion then
3317 -- fixed-point values must be read as integral values.
3319 Float_To_Int : constant Boolean :=
3320 Is_Floating_Point_Type (Expr_Type)
3321 and then Is_Integer_Type (Target_Type);
3323 begin
3324 if not Overflow_Checks_Suppressed (Target_Base)
3325 and then not Overflow_Checks_Suppressed (Target_Type)
3326 and then not
3327 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
3328 and then not Float_To_Int
3329 then
3330 Activate_Overflow_Check (N);
3331 end if;
3333 if not Range_Checks_Suppressed (Target_Type)
3334 and then not Range_Checks_Suppressed (Expr_Type)
3335 then
3336 if Float_To_Int then
3337 Apply_Float_Conversion_Check (Expr, Target_Type);
3338 else
3339 Apply_Scalar_Range_Check
3340 (Expr, Target_Type, Fixed_Int => Conv_OK);
3342 -- If the target type has predicates, we need to indicate
3343 -- the need for a check, even if Determine_Range finds that
3344 -- the value is within bounds. This may be the case e.g for
3345 -- a division with a constant denominator.
3347 if Has_Predicates (Target_Type) then
3348 Enable_Range_Check (Expr);
3349 end if;
3350 end if;
3351 end if;
3352 end;
3354 elsif Comes_From_Source (N)
3355 and then not Discriminant_Checks_Suppressed (Target_Type)
3356 and then Is_Record_Type (Target_Type)
3357 and then Is_Derived_Type (Target_Type)
3358 and then not Is_Tagged_Type (Target_Type)
3359 and then not Is_Constrained (Target_Type)
3360 and then Present (Stored_Constraint (Target_Type))
3361 then
3362 -- An unconstrained derived type may have inherited discriminant.
3363 -- Build an actual discriminant constraint list using the stored
3364 -- constraint, to verify that the expression of the parent type
3365 -- satisfies the constraints imposed by the (unconstrained) derived
3366 -- type. This applies to value conversions, not to view conversions
3367 -- of tagged types.
3369 declare
3370 Loc : constant Source_Ptr := Sloc (N);
3371 Cond : Node_Id;
3372 Constraint : Elmt_Id;
3373 Discr_Value : Node_Id;
3374 Discr : Entity_Id;
3376 New_Constraints : constant Elist_Id := New_Elmt_List;
3377 Old_Constraints : constant Elist_Id :=
3378 Discriminant_Constraint (Expr_Type);
3380 begin
3381 Constraint := First_Elmt (Stored_Constraint (Target_Type));
3382 while Present (Constraint) loop
3383 Discr_Value := Node (Constraint);
3385 if Is_Entity_Name (Discr_Value)
3386 and then Ekind (Entity (Discr_Value)) = E_Discriminant
3387 then
3388 Discr := Corresponding_Discriminant (Entity (Discr_Value));
3390 if Present (Discr)
3391 and then Scope (Discr) = Base_Type (Expr_Type)
3392 then
3393 -- Parent is constrained by new discriminant. Obtain
3394 -- Value of original discriminant in expression. If the
3395 -- new discriminant has been used to constrain more than
3396 -- one of the stored discriminants, this will provide the
3397 -- required consistency check.
3399 Append_Elmt
3400 (Make_Selected_Component (Loc,
3401 Prefix =>
3402 Duplicate_Subexpr_No_Checks
3403 (Expr, Name_Req => True),
3404 Selector_Name =>
3405 Make_Identifier (Loc, Chars (Discr))),
3406 New_Constraints);
3408 else
3409 -- Discriminant of more remote ancestor ???
3411 return;
3412 end if;
3414 -- Derived type definition has an explicit value for this
3415 -- stored discriminant.
3417 else
3418 Append_Elmt
3419 (Duplicate_Subexpr_No_Checks (Discr_Value),
3420 New_Constraints);
3421 end if;
3423 Next_Elmt (Constraint);
3424 end loop;
3426 -- Use the unconstrained expression type to retrieve the
3427 -- discriminants of the parent, and apply momentarily the
3428 -- discriminant constraint synthesized above.
3430 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
3431 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
3432 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
3434 Insert_Action (N,
3435 Make_Raise_Constraint_Error (Loc,
3436 Condition => Cond,
3437 Reason => CE_Discriminant_Check_Failed));
3438 end;
3440 -- For arrays, checks are set now, but conversions are applied during
3441 -- expansion, to take into accounts changes of representation. The
3442 -- checks become range checks on the base type or length checks on the
3443 -- subtype, depending on whether the target type is unconstrained or
3444 -- constrained. Note that the range check is put on the expression of a
3445 -- type conversion, while the length check is put on the type conversion
3446 -- itself.
3448 elsif Is_Array_Type (Target_Type) then
3449 if Is_Constrained (Target_Type) then
3450 Set_Do_Length_Check (N);
3451 else
3452 Set_Do_Range_Check (Expr);
3453 end if;
3454 end if;
3455 end Apply_Type_Conversion_Checks;
3457 ----------------------------------------------
3458 -- Apply_Universal_Integer_Attribute_Checks --
3459 ----------------------------------------------
3461 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
3462 Loc : constant Source_Ptr := Sloc (N);
3463 Typ : constant Entity_Id := Etype (N);
3465 begin
3466 if Inside_A_Generic then
3467 return;
3469 -- Nothing to do if checks are suppressed
3471 elsif Range_Checks_Suppressed (Typ)
3472 and then Overflow_Checks_Suppressed (Typ)
3473 then
3474 return;
3476 -- Nothing to do if the attribute does not come from source. The
3477 -- internal attributes we generate of this type do not need checks,
3478 -- and furthermore the attempt to check them causes some circular
3479 -- elaboration orders when dealing with packed types.
3481 elsif not Comes_From_Source (N) then
3482 return;
3484 -- If the prefix is a selected component that depends on a discriminant
3485 -- the check may improperly expose a discriminant instead of using
3486 -- the bounds of the object itself. Set the type of the attribute to
3487 -- the base type of the context, so that a check will be imposed when
3488 -- needed (e.g. if the node appears as an index).
3490 elsif Nkind (Prefix (N)) = N_Selected_Component
3491 and then Ekind (Typ) = E_Signed_Integer_Subtype
3492 and then Depends_On_Discriminant (Scalar_Range (Typ))
3493 then
3494 Set_Etype (N, Base_Type (Typ));
3496 -- Otherwise, replace the attribute node with a type conversion node
3497 -- whose expression is the attribute, retyped to universal integer, and
3498 -- whose subtype mark is the target type. The call to analyze this
3499 -- conversion will set range and overflow checks as required for proper
3500 -- detection of an out of range value.
3502 else
3503 Set_Etype (N, Universal_Integer);
3504 Set_Analyzed (N, True);
3506 Rewrite (N,
3507 Make_Type_Conversion (Loc,
3508 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
3509 Expression => Relocate_Node (N)));
3511 Analyze_And_Resolve (N, Typ);
3512 return;
3513 end if;
3514 end Apply_Universal_Integer_Attribute_Checks;
3516 -------------------------------------
3517 -- Atomic_Synchronization_Disabled --
3518 -------------------------------------
3520 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3521 -- using a bogus check called Atomic_Synchronization. This is to make it
3522 -- more convenient to get exactly the same semantics as [Un]Suppress.
3524 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
3525 begin
3526 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3527 -- looks enabled, since it is never disabled.
3529 if Debug_Flag_Dot_E then
3530 return False;
3532 -- If debug flag d.d is set then always return True, i.e. all atomic
3533 -- sync looks disabled, since it always tests True.
3535 elsif Debug_Flag_Dot_D then
3536 return True;
3538 -- If entity present, then check result for that entity
3540 elsif Present (E) and then Checks_May_Be_Suppressed (E) then
3541 return Is_Check_Suppressed (E, Atomic_Synchronization);
3543 -- Otherwise result depends on current scope setting
3545 else
3546 return Scope_Suppress.Suppress (Atomic_Synchronization);
3547 end if;
3548 end Atomic_Synchronization_Disabled;
3550 -------------------------------
3551 -- Build_Discriminant_Checks --
3552 -------------------------------
3554 function Build_Discriminant_Checks
3555 (N : Node_Id;
3556 T_Typ : Entity_Id) return Node_Id
3558 Loc : constant Source_Ptr := Sloc (N);
3559 Cond : Node_Id;
3560 Disc : Elmt_Id;
3561 Disc_Ent : Entity_Id;
3562 Dref : Node_Id;
3563 Dval : Node_Id;
3565 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
3567 ----------------------------------
3568 -- Aggregate_Discriminant_Value --
3569 ----------------------------------
3571 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
3572 Assoc : Node_Id;
3574 begin
3575 -- The aggregate has been normalized with named associations. We use
3576 -- the Chars field to locate the discriminant to take into account
3577 -- discriminants in derived types, which carry the same name as those
3578 -- in the parent.
3580 Assoc := First (Component_Associations (N));
3581 while Present (Assoc) loop
3582 if Chars (First (Choices (Assoc))) = Chars (Disc) then
3583 return Expression (Assoc);
3584 else
3585 Next (Assoc);
3586 end if;
3587 end loop;
3589 -- Discriminant must have been found in the loop above
3591 raise Program_Error;
3592 end Aggregate_Discriminant_Val;
3594 -- Start of processing for Build_Discriminant_Checks
3596 begin
3597 -- Loop through discriminants evolving the condition
3599 Cond := Empty;
3600 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
3602 -- For a fully private type, use the discriminants of the parent type
3604 if Is_Private_Type (T_Typ)
3605 and then No (Full_View (T_Typ))
3606 then
3607 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
3608 else
3609 Disc_Ent := First_Discriminant (T_Typ);
3610 end if;
3612 while Present (Disc) loop
3613 Dval := Node (Disc);
3615 if Nkind (Dval) = N_Identifier
3616 and then Ekind (Entity (Dval)) = E_Discriminant
3617 then
3618 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
3619 else
3620 Dval := Duplicate_Subexpr_No_Checks (Dval);
3621 end if;
3623 -- If we have an Unchecked_Union node, we can infer the discriminants
3624 -- of the node.
3626 if Is_Unchecked_Union (Base_Type (T_Typ)) then
3627 Dref := New_Copy (
3628 Get_Discriminant_Value (
3629 First_Discriminant (T_Typ),
3630 T_Typ,
3631 Stored_Constraint (T_Typ)));
3633 elsif Nkind (N) = N_Aggregate then
3634 Dref :=
3635 Duplicate_Subexpr_No_Checks
3636 (Aggregate_Discriminant_Val (Disc_Ent));
3638 else
3639 Dref :=
3640 Make_Selected_Component (Loc,
3641 Prefix =>
3642 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
3643 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
3645 Set_Is_In_Discriminant_Check (Dref);
3646 end if;
3648 Evolve_Or_Else (Cond,
3649 Make_Op_Ne (Loc,
3650 Left_Opnd => Dref,
3651 Right_Opnd => Dval));
3653 Next_Elmt (Disc);
3654 Next_Discriminant (Disc_Ent);
3655 end loop;
3657 return Cond;
3658 end Build_Discriminant_Checks;
3660 ------------------
3661 -- Check_Needed --
3662 ------------------
3664 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
3665 N : Node_Id;
3666 P : Node_Id;
3667 K : Node_Kind;
3668 L : Node_Id;
3669 R : Node_Id;
3671 function Left_Expression (Op : Node_Id) return Node_Id;
3672 -- Return the relevant expression from the left operand of the given
3673 -- short circuit form: this is LO itself, except if LO is a qualified
3674 -- expression, a type conversion, or an expression with actions, in
3675 -- which case this is Left_Expression (Expression (LO)).
3677 ---------------------
3678 -- Left_Expression --
3679 ---------------------
3681 function Left_Expression (Op : Node_Id) return Node_Id is
3682 LE : Node_Id := Left_Opnd (Op);
3683 begin
3684 while Nkind_In (LE, N_Qualified_Expression,
3685 N_Type_Conversion,
3686 N_Expression_With_Actions)
3687 loop
3688 LE := Expression (LE);
3689 end loop;
3691 return LE;
3692 end Left_Expression;
3694 -- Start of processing for Check_Needed
3696 begin
3697 -- Always check if not simple entity
3699 if Nkind (Nod) not in N_Has_Entity
3700 or else not Comes_From_Source (Nod)
3701 then
3702 return True;
3703 end if;
3705 -- Look up tree for short circuit
3707 N := Nod;
3708 loop
3709 P := Parent (N);
3710 K := Nkind (P);
3712 -- Done if out of subexpression (note that we allow generated stuff
3713 -- such as itype declarations in this context, to keep the loop going
3714 -- since we may well have generated such stuff in complex situations.
3715 -- Also done if no parent (probably an error condition, but no point
3716 -- in behaving nasty if we find it).
3718 if No (P)
3719 or else (K not in N_Subexpr and then Comes_From_Source (P))
3720 then
3721 return True;
3723 -- Or/Or Else case, where test is part of the right operand, or is
3724 -- part of one of the actions associated with the right operand, and
3725 -- the left operand is an equality test.
3727 elsif K = N_Op_Or then
3728 exit when N = Right_Opnd (P)
3729 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3731 elsif K = N_Or_Else then
3732 exit when (N = Right_Opnd (P)
3733 or else
3734 (Is_List_Member (N)
3735 and then List_Containing (N) = Actions (P)))
3736 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3738 -- Similar test for the And/And then case, where the left operand
3739 -- is an inequality test.
3741 elsif K = N_Op_And then
3742 exit when N = Right_Opnd (P)
3743 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3745 elsif K = N_And_Then then
3746 exit when (N = Right_Opnd (P)
3747 or else
3748 (Is_List_Member (N)
3749 and then List_Containing (N) = Actions (P)))
3750 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3751 end if;
3753 N := P;
3754 end loop;
3756 -- If we fall through the loop, then we have a conditional with an
3757 -- appropriate test as its left operand, so look further.
3759 L := Left_Expression (P);
3761 -- L is an "=" or "/=" operator: extract its operands
3763 R := Right_Opnd (L);
3764 L := Left_Opnd (L);
3766 -- Left operand of test must match original variable
3768 if Nkind (L) not in N_Has_Entity or else Entity (L) /= Entity (Nod) then
3769 return True;
3770 end if;
3772 -- Right operand of test must be key value (zero or null)
3774 case Check is
3775 when Access_Check =>
3776 if not Known_Null (R) then
3777 return True;
3778 end if;
3780 when Division_Check =>
3781 if not Compile_Time_Known_Value (R)
3782 or else Expr_Value (R) /= Uint_0
3783 then
3784 return True;
3785 end if;
3787 when others =>
3788 raise Program_Error;
3789 end case;
3791 -- Here we have the optimizable case, warn if not short-circuited
3793 if K = N_Op_And or else K = N_Op_Or then
3794 Error_Msg_Warn := SPARK_Mode /= On;
3796 case Check is
3797 when Access_Check =>
3798 if GNATprove_Mode then
3799 Error_Msg_N
3800 ("Constraint_Error might have been raised (access check)",
3801 Parent (Nod));
3802 else
3803 Error_Msg_N
3804 ("Constraint_Error may be raised (access check)??",
3805 Parent (Nod));
3806 end if;
3808 when Division_Check =>
3809 if GNATprove_Mode then
3810 Error_Msg_N
3811 ("Constraint_Error might have been raised (zero divide)",
3812 Parent (Nod));
3813 else
3814 Error_Msg_N
3815 ("Constraint_Error may be raised (zero divide)??",
3816 Parent (Nod));
3817 end if;
3819 when others =>
3820 raise Program_Error;
3821 end case;
3823 if K = N_Op_And then
3824 Error_Msg_N -- CODEFIX
3825 ("use `AND THEN` instead of AND??", P);
3826 else
3827 Error_Msg_N -- CODEFIX
3828 ("use `OR ELSE` instead of OR??", P);
3829 end if;
3831 -- If not short-circuited, we need the check
3833 return True;
3835 -- If short-circuited, we can omit the check
3837 else
3838 return False;
3839 end if;
3840 end Check_Needed;
3842 -----------------------------------
3843 -- Check_Valid_Lvalue_Subscripts --
3844 -----------------------------------
3846 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
3847 begin
3848 -- Skip this if range checks are suppressed
3850 if Range_Checks_Suppressed (Etype (Expr)) then
3851 return;
3853 -- Only do this check for expressions that come from source. We assume
3854 -- that expander generated assignments explicitly include any necessary
3855 -- checks. Note that this is not just an optimization, it avoids
3856 -- infinite recursions.
3858 elsif not Comes_From_Source (Expr) then
3859 return;
3861 -- For a selected component, check the prefix
3863 elsif Nkind (Expr) = N_Selected_Component then
3864 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
3865 return;
3867 -- Case of indexed component
3869 elsif Nkind (Expr) = N_Indexed_Component then
3870 Apply_Subscript_Validity_Checks (Expr);
3872 -- Prefix may itself be or contain an indexed component, and these
3873 -- subscripts need checking as well.
3875 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
3876 end if;
3877 end Check_Valid_Lvalue_Subscripts;
3879 ----------------------------------
3880 -- Null_Exclusion_Static_Checks --
3881 ----------------------------------
3883 procedure Null_Exclusion_Static_Checks (N : Node_Id) is
3884 Error_Node : Node_Id;
3885 Expr : Node_Id;
3886 Has_Null : constant Boolean := Has_Null_Exclusion (N);
3887 K : constant Node_Kind := Nkind (N);
3888 Typ : Entity_Id;
3890 begin
3891 pragma Assert
3892 (Nkind_In (K, N_Component_Declaration,
3893 N_Discriminant_Specification,
3894 N_Function_Specification,
3895 N_Object_Declaration,
3896 N_Parameter_Specification));
3898 if K = N_Function_Specification then
3899 Typ := Etype (Defining_Entity (N));
3900 else
3901 Typ := Etype (Defining_Identifier (N));
3902 end if;
3904 case K is
3905 when N_Component_Declaration =>
3906 if Present (Access_Definition (Component_Definition (N))) then
3907 Error_Node := Component_Definition (N);
3908 else
3909 Error_Node := Subtype_Indication (Component_Definition (N));
3910 end if;
3912 when N_Discriminant_Specification =>
3913 Error_Node := Discriminant_Type (N);
3915 when N_Function_Specification =>
3916 Error_Node := Result_Definition (N);
3918 when N_Object_Declaration =>
3919 Error_Node := Object_Definition (N);
3921 when N_Parameter_Specification =>
3922 Error_Node := Parameter_Type (N);
3924 when others =>
3925 raise Program_Error;
3926 end case;
3928 if Has_Null then
3930 -- Enforce legality rule 3.10 (13): A null exclusion can only be
3931 -- applied to an access [sub]type.
3933 if not Is_Access_Type (Typ) then
3934 Error_Msg_N
3935 ("`NOT NULL` allowed only for an access type", Error_Node);
3937 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
3938 -- be applied to a [sub]type that does not exclude null already.
3940 elsif Can_Never_Be_Null (Typ)
3941 and then Comes_From_Source (Typ)
3942 then
3943 Error_Msg_NE
3944 ("`NOT NULL` not allowed (& already excludes null)",
3945 Error_Node, Typ);
3946 end if;
3947 end if;
3949 -- Check that null-excluding objects are always initialized, except for
3950 -- deferred constants, for which the expression will appear in the full
3951 -- declaration.
3953 if K = N_Object_Declaration
3954 and then No (Expression (N))
3955 and then not Constant_Present (N)
3956 and then not No_Initialization (N)
3957 then
3958 -- Add an expression that assigns null. This node is needed by
3959 -- Apply_Compile_Time_Constraint_Error, which will replace this with
3960 -- a Constraint_Error node.
3962 Set_Expression (N, Make_Null (Sloc (N)));
3963 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
3965 Apply_Compile_Time_Constraint_Error
3966 (N => Expression (N),
3967 Msg =>
3968 "(Ada 2005) null-excluding objects must be initialized??",
3969 Reason => CE_Null_Not_Allowed);
3970 end if;
3972 -- Check that a null-excluding component, formal or object is not being
3973 -- assigned a null value. Otherwise generate a warning message and
3974 -- replace Expression (N) by an N_Constraint_Error node.
3976 if K /= N_Function_Specification then
3977 Expr := Expression (N);
3979 if Present (Expr) and then Known_Null (Expr) then
3980 case K is
3981 when N_Component_Declaration |
3982 N_Discriminant_Specification =>
3983 Apply_Compile_Time_Constraint_Error
3984 (N => Expr,
3985 Msg => "(Ada 2005) null not allowed "
3986 & "in null-excluding components??",
3987 Reason => CE_Null_Not_Allowed);
3989 when N_Object_Declaration =>
3990 Apply_Compile_Time_Constraint_Error
3991 (N => Expr,
3992 Msg => "(Ada 2005) null not allowed "
3993 & "in null-excluding objects??",
3994 Reason => CE_Null_Not_Allowed);
3996 when N_Parameter_Specification =>
3997 Apply_Compile_Time_Constraint_Error
3998 (N => Expr,
3999 Msg => "(Ada 2005) null not allowed "
4000 & "in null-excluding formals??",
4001 Reason => CE_Null_Not_Allowed);
4003 when others =>
4004 null;
4005 end case;
4006 end if;
4007 end if;
4008 end Null_Exclusion_Static_Checks;
4010 ----------------------------------
4011 -- Conditional_Statements_Begin --
4012 ----------------------------------
4014 procedure Conditional_Statements_Begin is
4015 begin
4016 Saved_Checks_TOS := Saved_Checks_TOS + 1;
4018 -- If stack overflows, kill all checks, that way we know to simply reset
4019 -- the number of saved checks to zero on return. This should never occur
4020 -- in practice.
4022 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4023 Kill_All_Checks;
4025 -- In the normal case, we just make a new stack entry saving the current
4026 -- number of saved checks for a later restore.
4028 else
4029 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
4031 if Debug_Flag_CC then
4032 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
4033 Num_Saved_Checks);
4034 end if;
4035 end if;
4036 end Conditional_Statements_Begin;
4038 --------------------------------
4039 -- Conditional_Statements_End --
4040 --------------------------------
4042 procedure Conditional_Statements_End is
4043 begin
4044 pragma Assert (Saved_Checks_TOS > 0);
4046 -- If the saved checks stack overflowed, then we killed all checks, so
4047 -- setting the number of saved checks back to zero is correct. This
4048 -- should never occur in practice.
4050 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4051 Num_Saved_Checks := 0;
4053 -- In the normal case, restore the number of saved checks from the top
4054 -- stack entry.
4056 else
4057 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
4059 if Debug_Flag_CC then
4060 w ("Conditional_Statements_End: Num_Saved_Checks = ",
4061 Num_Saved_Checks);
4062 end if;
4063 end if;
4065 Saved_Checks_TOS := Saved_Checks_TOS - 1;
4066 end Conditional_Statements_End;
4068 -------------------------
4069 -- Convert_From_Bignum --
4070 -------------------------
4072 function Convert_From_Bignum (N : Node_Id) return Node_Id is
4073 Loc : constant Source_Ptr := Sloc (N);
4075 begin
4076 pragma Assert (Is_RTE (Etype (N), RE_Bignum));
4078 -- Construct call From Bignum
4080 return
4081 Make_Function_Call (Loc,
4082 Name =>
4083 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4084 Parameter_Associations => New_List (Relocate_Node (N)));
4085 end Convert_From_Bignum;
4087 -----------------------
4088 -- Convert_To_Bignum --
4089 -----------------------
4091 function Convert_To_Bignum (N : Node_Id) return Node_Id is
4092 Loc : constant Source_Ptr := Sloc (N);
4094 begin
4095 -- Nothing to do if Bignum already except call Relocate_Node
4097 if Is_RTE (Etype (N), RE_Bignum) then
4098 return Relocate_Node (N);
4100 -- Otherwise construct call to To_Bignum, converting the operand to the
4101 -- required Long_Long_Integer form.
4103 else
4104 pragma Assert (Is_Signed_Integer_Type (Etype (N)));
4105 return
4106 Make_Function_Call (Loc,
4107 Name =>
4108 New_Occurrence_Of (RTE (RE_To_Bignum), Loc),
4109 Parameter_Associations => New_List (
4110 Convert_To (Standard_Long_Long_Integer, Relocate_Node (N))));
4111 end if;
4112 end Convert_To_Bignum;
4114 ---------------------
4115 -- Determine_Range --
4116 ---------------------
4118 Cache_Size : constant := 2 ** 10;
4119 type Cache_Index is range 0 .. Cache_Size - 1;
4120 -- Determine size of below cache (power of 2 is more efficient)
4122 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
4123 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
4124 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
4125 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
4126 Determine_Range_Cache_Lo_R : array (Cache_Index) of Ureal;
4127 Determine_Range_Cache_Hi_R : array (Cache_Index) of Ureal;
4128 -- The above arrays are used to implement a small direct cache for
4129 -- Determine_Range and Determine_Range_R calls. Because of the way these
4130 -- subprograms recursively traces subexpressions, and because overflow
4131 -- checking calls the routine on the way up the tree, a quadratic behavior
4132 -- can otherwise be encountered in large expressions. The cache entry for
4133 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4134 -- by checking the actual node value stored there. The Range_Cache_V array
4135 -- records the setting of Assume_Valid for the cache entry.
4137 procedure Determine_Range
4138 (N : Node_Id;
4139 OK : out Boolean;
4140 Lo : out Uint;
4141 Hi : out Uint;
4142 Assume_Valid : Boolean := False)
4144 Typ : Entity_Id := Etype (N);
4145 -- Type to use, may get reset to base type for possibly invalid entity
4147 Lo_Left : Uint;
4148 Hi_Left : Uint;
4149 -- Lo and Hi bounds of left operand
4151 Lo_Right : Uint;
4152 Hi_Right : Uint;
4153 -- Lo and Hi bounds of right (or only) operand
4155 Bound : Node_Id;
4156 -- Temp variable used to hold a bound node
4158 Hbound : Uint;
4159 -- High bound of base type of expression
4161 Lor : Uint;
4162 Hir : Uint;
4163 -- Refined values for low and high bounds, after tightening
4165 OK1 : Boolean;
4166 -- Used in lower level calls to indicate if call succeeded
4168 Cindex : Cache_Index;
4169 -- Used to search cache
4171 Btyp : Entity_Id;
4172 -- Base type
4174 function OK_Operands return Boolean;
4175 -- Used for binary operators. Determines the ranges of the left and
4176 -- right operands, and if they are both OK, returns True, and puts
4177 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4179 -----------------
4180 -- OK_Operands --
4181 -----------------
4183 function OK_Operands return Boolean is
4184 begin
4185 Determine_Range
4186 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4188 if not OK1 then
4189 return False;
4190 end if;
4192 Determine_Range
4193 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4194 return OK1;
4195 end OK_Operands;
4197 -- Start of processing for Determine_Range
4199 begin
4200 -- Prevent junk warnings by initializing range variables
4202 Lo := No_Uint;
4203 Hi := No_Uint;
4204 Lor := No_Uint;
4205 Hir := No_Uint;
4207 -- For temporary constants internally generated to remove side effects
4208 -- we must use the corresponding expression to determine the range of
4209 -- the expression. But note that the expander can also generate
4210 -- constants in other cases, including deferred constants.
4212 if Is_Entity_Name (N)
4213 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
4214 and then Ekind (Entity (N)) = E_Constant
4215 and then Is_Internal_Name (Chars (Entity (N)))
4216 then
4217 if Present (Expression (Parent (Entity (N)))) then
4218 Determine_Range
4219 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
4221 elsif Present (Full_View (Entity (N))) then
4222 Determine_Range
4223 (Expression (Parent (Full_View (Entity (N)))),
4224 OK, Lo, Hi, Assume_Valid);
4226 else
4227 OK := False;
4228 end if;
4229 return;
4230 end if;
4232 -- If type is not defined, we can't determine its range
4234 if No (Typ)
4236 -- We don't deal with anything except discrete types
4238 or else not Is_Discrete_Type (Typ)
4240 -- Ignore type for which an error has been posted, since range in
4241 -- this case may well be a bogosity deriving from the error. Also
4242 -- ignore if error posted on the reference node.
4244 or else Error_Posted (N) or else Error_Posted (Typ)
4245 then
4246 OK := False;
4247 return;
4248 end if;
4250 -- For all other cases, we can determine the range
4252 OK := True;
4254 -- If value is compile time known, then the possible range is the one
4255 -- value that we know this expression definitely has.
4257 if Compile_Time_Known_Value (N) then
4258 Lo := Expr_Value (N);
4259 Hi := Lo;
4260 return;
4261 end if;
4263 -- Return if already in the cache
4265 Cindex := Cache_Index (N mod Cache_Size);
4267 if Determine_Range_Cache_N (Cindex) = N
4268 and then
4269 Determine_Range_Cache_V (Cindex) = Assume_Valid
4270 then
4271 Lo := Determine_Range_Cache_Lo (Cindex);
4272 Hi := Determine_Range_Cache_Hi (Cindex);
4273 return;
4274 end if;
4276 -- Otherwise, start by finding the bounds of the type of the expression,
4277 -- the value cannot be outside this range (if it is, then we have an
4278 -- overflow situation, which is a separate check, we are talking here
4279 -- only about the expression value).
4281 -- First a check, never try to find the bounds of a generic type, since
4282 -- these bounds are always junk values, and it is only valid to look at
4283 -- the bounds in an instance.
4285 if Is_Generic_Type (Typ) then
4286 OK := False;
4287 return;
4288 end if;
4290 -- First step, change to use base type unless we know the value is valid
4292 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
4293 or else Assume_No_Invalid_Values
4294 or else Assume_Valid
4295 then
4296 null;
4297 else
4298 Typ := Underlying_Type (Base_Type (Typ));
4299 end if;
4301 -- Retrieve the base type. Handle the case where the base type is a
4302 -- private enumeration type.
4304 Btyp := Base_Type (Typ);
4306 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
4307 Btyp := Full_View (Btyp);
4308 end if;
4310 -- We use the actual bound unless it is dynamic, in which case use the
4311 -- corresponding base type bound if possible. If we can't get a bound
4312 -- then we figure we can't determine the range (a peculiar case, that
4313 -- perhaps cannot happen, but there is no point in bombing in this
4314 -- optimization circuit.
4316 -- First the low bound
4318 Bound := Type_Low_Bound (Typ);
4320 if Compile_Time_Known_Value (Bound) then
4321 Lo := Expr_Value (Bound);
4323 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
4324 Lo := Expr_Value (Type_Low_Bound (Btyp));
4326 else
4327 OK := False;
4328 return;
4329 end if;
4331 -- Now the high bound
4333 Bound := Type_High_Bound (Typ);
4335 -- We need the high bound of the base type later on, and this should
4336 -- always be compile time known. Again, it is not clear that this
4337 -- can ever be false, but no point in bombing.
4339 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
4340 Hbound := Expr_Value (Type_High_Bound (Btyp));
4341 Hi := Hbound;
4343 else
4344 OK := False;
4345 return;
4346 end if;
4348 -- If we have a static subtype, then that may have a tighter bound so
4349 -- use the upper bound of the subtype instead in this case.
4351 if Compile_Time_Known_Value (Bound) then
4352 Hi := Expr_Value (Bound);
4353 end if;
4355 -- We may be able to refine this value in certain situations. If any
4356 -- refinement is possible, then Lor and Hir are set to possibly tighter
4357 -- bounds, and OK1 is set to True.
4359 case Nkind (N) is
4361 -- For unary plus, result is limited by range of operand
4363 when N_Op_Plus =>
4364 Determine_Range
4365 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
4367 -- For unary minus, determine range of operand, and negate it
4369 when N_Op_Minus =>
4370 Determine_Range
4371 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4373 if OK1 then
4374 Lor := -Hi_Right;
4375 Hir := -Lo_Right;
4376 end if;
4378 -- For binary addition, get range of each operand and do the
4379 -- addition to get the result range.
4381 when N_Op_Add =>
4382 if OK_Operands then
4383 Lor := Lo_Left + Lo_Right;
4384 Hir := Hi_Left + Hi_Right;
4385 end if;
4387 -- Division is tricky. The only case we consider is where the right
4388 -- operand is a positive constant, and in this case we simply divide
4389 -- the bounds of the left operand
4391 when N_Op_Divide =>
4392 if OK_Operands then
4393 if Lo_Right = Hi_Right
4394 and then Lo_Right > 0
4395 then
4396 Lor := Lo_Left / Lo_Right;
4397 Hir := Hi_Left / Lo_Right;
4398 else
4399 OK1 := False;
4400 end if;
4401 end if;
4403 -- For binary subtraction, get range of each operand and do the worst
4404 -- case subtraction to get the result range.
4406 when N_Op_Subtract =>
4407 if OK_Operands then
4408 Lor := Lo_Left - Hi_Right;
4409 Hir := Hi_Left - Lo_Right;
4410 end if;
4412 -- For MOD, if right operand is a positive constant, then result must
4413 -- be in the allowable range of mod results.
4415 when N_Op_Mod =>
4416 if OK_Operands then
4417 if Lo_Right = Hi_Right
4418 and then Lo_Right /= 0
4419 then
4420 if Lo_Right > 0 then
4421 Lor := Uint_0;
4422 Hir := Lo_Right - 1;
4424 else -- Lo_Right < 0
4425 Lor := Lo_Right + 1;
4426 Hir := Uint_0;
4427 end if;
4429 else
4430 OK1 := False;
4431 end if;
4432 end if;
4434 -- For REM, if right operand is a positive constant, then result must
4435 -- be in the allowable range of mod results.
4437 when N_Op_Rem =>
4438 if OK_Operands then
4439 if Lo_Right = Hi_Right
4440 and then Lo_Right /= 0
4441 then
4442 declare
4443 Dval : constant Uint := (abs Lo_Right) - 1;
4445 begin
4446 -- The sign of the result depends on the sign of the
4447 -- dividend (but not on the sign of the divisor, hence
4448 -- the abs operation above).
4450 if Lo_Left < 0 then
4451 Lor := -Dval;
4452 else
4453 Lor := Uint_0;
4454 end if;
4456 if Hi_Left < 0 then
4457 Hir := Uint_0;
4458 else
4459 Hir := Dval;
4460 end if;
4461 end;
4463 else
4464 OK1 := False;
4465 end if;
4466 end if;
4468 -- Attribute reference cases
4470 when N_Attribute_Reference =>
4471 case Attribute_Name (N) is
4473 -- For Pos/Val attributes, we can refine the range using the
4474 -- possible range of values of the attribute expression.
4476 when Name_Pos | Name_Val =>
4477 Determine_Range
4478 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
4480 -- For Length attribute, use the bounds of the corresponding
4481 -- index type to refine the range.
4483 when Name_Length =>
4484 declare
4485 Atyp : Entity_Id := Etype (Prefix (N));
4486 Inum : Nat;
4487 Indx : Node_Id;
4489 LL, LU : Uint;
4490 UL, UU : Uint;
4492 begin
4493 if Is_Access_Type (Atyp) then
4494 Atyp := Designated_Type (Atyp);
4495 end if;
4497 -- For string literal, we know exact value
4499 if Ekind (Atyp) = E_String_Literal_Subtype then
4500 OK := True;
4501 Lo := String_Literal_Length (Atyp);
4502 Hi := String_Literal_Length (Atyp);
4503 return;
4504 end if;
4506 -- Otherwise check for expression given
4508 if No (Expressions (N)) then
4509 Inum := 1;
4510 else
4511 Inum :=
4512 UI_To_Int (Expr_Value (First (Expressions (N))));
4513 end if;
4515 Indx := First_Index (Atyp);
4516 for J in 2 .. Inum loop
4517 Indx := Next_Index (Indx);
4518 end loop;
4520 -- If the index type is a formal type or derived from
4521 -- one, the bounds are not static.
4523 if Is_Generic_Type (Root_Type (Etype (Indx))) then
4524 OK := False;
4525 return;
4526 end if;
4528 Determine_Range
4529 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
4530 Assume_Valid);
4532 if OK1 then
4533 Determine_Range
4534 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
4535 Assume_Valid);
4537 if OK1 then
4539 -- The maximum value for Length is the biggest
4540 -- possible gap between the values of the bounds.
4541 -- But of course, this value cannot be negative.
4543 Hir := UI_Max (Uint_0, UU - LL + 1);
4545 -- For constrained arrays, the minimum value for
4546 -- Length is taken from the actual value of the
4547 -- bounds, since the index will be exactly of this
4548 -- subtype.
4550 if Is_Constrained (Atyp) then
4551 Lor := UI_Max (Uint_0, UL - LU + 1);
4553 -- For an unconstrained array, the minimum value
4554 -- for length is always zero.
4556 else
4557 Lor := Uint_0;
4558 end if;
4559 end if;
4560 end if;
4561 end;
4563 -- No special handling for other attributes
4564 -- Probably more opportunities exist here???
4566 when others =>
4567 OK1 := False;
4569 end case;
4571 -- For type conversion from one discrete type to another, we can
4572 -- refine the range using the converted value.
4574 when N_Type_Conversion =>
4575 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
4577 -- Nothing special to do for all other expression kinds
4579 when others =>
4580 OK1 := False;
4581 Lor := No_Uint;
4582 Hir := No_Uint;
4583 end case;
4585 -- At this stage, if OK1 is true, then we know that the actual result of
4586 -- the computed expression is in the range Lor .. Hir. We can use this
4587 -- to restrict the possible range of results.
4589 if OK1 then
4591 -- If the refined value of the low bound is greater than the type
4592 -- low bound, then reset it to the more restrictive value. However,
4593 -- we do NOT do this for the case of a modular type where the
4594 -- possible upper bound on the value is above the base type high
4595 -- bound, because that means the result could wrap.
4597 if Lor > Lo
4598 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
4599 then
4600 Lo := Lor;
4601 end if;
4603 -- Similarly, if the refined value of the high bound is less than the
4604 -- value so far, then reset it to the more restrictive value. Again,
4605 -- we do not do this if the refined low bound is negative for a
4606 -- modular type, since this would wrap.
4608 if Hir < Hi
4609 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
4610 then
4611 Hi := Hir;
4612 end if;
4613 end if;
4615 -- Set cache entry for future call and we are all done
4617 Determine_Range_Cache_N (Cindex) := N;
4618 Determine_Range_Cache_V (Cindex) := Assume_Valid;
4619 Determine_Range_Cache_Lo (Cindex) := Lo;
4620 Determine_Range_Cache_Hi (Cindex) := Hi;
4621 return;
4623 -- If any exception occurs, it means that we have some bug in the compiler,
4624 -- possibly triggered by a previous error, or by some unforeseen peculiar
4625 -- occurrence. However, this is only an optimization attempt, so there is
4626 -- really no point in crashing the compiler. Instead we just decide, too
4627 -- bad, we can't figure out a range in this case after all.
4629 exception
4630 when others =>
4632 -- Debug flag K disables this behavior (useful for debugging)
4634 if Debug_Flag_K then
4635 raise;
4636 else
4637 OK := False;
4638 Lo := No_Uint;
4639 Hi := No_Uint;
4640 return;
4641 end if;
4642 end Determine_Range;
4644 -----------------------
4645 -- Determine_Range_R --
4646 -----------------------
4648 procedure Determine_Range_R
4649 (N : Node_Id;
4650 OK : out Boolean;
4651 Lo : out Ureal;
4652 Hi : out Ureal;
4653 Assume_Valid : Boolean := False)
4655 Typ : Entity_Id := Etype (N);
4656 -- Type to use, may get reset to base type for possibly invalid entity
4658 Lo_Left : Ureal;
4659 Hi_Left : Ureal;
4660 -- Lo and Hi bounds of left operand
4662 Lo_Right : Ureal;
4663 Hi_Right : Ureal;
4664 -- Lo and Hi bounds of right (or only) operand
4666 Bound : Node_Id;
4667 -- Temp variable used to hold a bound node
4669 Hbound : Ureal;
4670 -- High bound of base type of expression
4672 Lor : Ureal;
4673 Hir : Ureal;
4674 -- Refined values for low and high bounds, after tightening
4676 OK1 : Boolean;
4677 -- Used in lower level calls to indicate if call succeeded
4679 Cindex : Cache_Index;
4680 -- Used to search cache
4682 Btyp : Entity_Id;
4683 -- Base type
4685 function OK_Operands return Boolean;
4686 -- Used for binary operators. Determines the ranges of the left and
4687 -- right operands, and if they are both OK, returns True, and puts
4688 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4690 function Round_Machine (B : Ureal) return Ureal;
4691 -- B is a real bound. Round it using mode Round_Even.
4693 -----------------
4694 -- OK_Operands --
4695 -----------------
4697 function OK_Operands return Boolean is
4698 begin
4699 Determine_Range_R
4700 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4702 if not OK1 then
4703 return False;
4704 end if;
4706 Determine_Range_R
4707 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4708 return OK1;
4709 end OK_Operands;
4711 -------------------
4712 -- Round_Machine --
4713 -------------------
4715 function Round_Machine (B : Ureal) return Ureal is
4716 begin
4717 return Machine (Typ, B, Round_Even, N);
4718 end Round_Machine;
4720 -- Start of processing for Determine_Range_R
4722 begin
4723 -- Prevent junk warnings by initializing range variables
4725 Lo := No_Ureal;
4726 Hi := No_Ureal;
4727 Lor := No_Ureal;
4728 Hir := No_Ureal;
4730 -- For temporary constants internally generated to remove side effects
4731 -- we must use the corresponding expression to determine the range of
4732 -- the expression. But note that the expander can also generate
4733 -- constants in other cases, including deferred constants.
4735 if Is_Entity_Name (N)
4736 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
4737 and then Ekind (Entity (N)) = E_Constant
4738 and then Is_Internal_Name (Chars (Entity (N)))
4739 then
4740 if Present (Expression (Parent (Entity (N)))) then
4741 Determine_Range_R
4742 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
4744 elsif Present (Full_View (Entity (N))) then
4745 Determine_Range_R
4746 (Expression (Parent (Full_View (Entity (N)))),
4747 OK, Lo, Hi, Assume_Valid);
4749 else
4750 OK := False;
4751 end if;
4753 return;
4754 end if;
4756 -- If type is not defined, we can't determine its range
4758 if No (Typ)
4760 -- We don't deal with anything except IEEE floating-point types
4762 or else not Is_Floating_Point_Type (Typ)
4763 or else Float_Rep (Typ) /= IEEE_Binary
4765 -- Ignore type for which an error has been posted, since range in
4766 -- this case may well be a bogosity deriving from the error. Also
4767 -- ignore if error posted on the reference node.
4769 or else Error_Posted (N) or else Error_Posted (Typ)
4770 then
4771 OK := False;
4772 return;
4773 end if;
4775 -- For all other cases, we can determine the range
4777 OK := True;
4779 -- If value is compile time known, then the possible range is the one
4780 -- value that we know this expression definitely has.
4782 if Compile_Time_Known_Value (N) then
4783 Lo := Expr_Value_R (N);
4784 Hi := Lo;
4785 return;
4786 end if;
4788 -- Return if already in the cache
4790 Cindex := Cache_Index (N mod Cache_Size);
4792 if Determine_Range_Cache_N (Cindex) = N
4793 and then
4794 Determine_Range_Cache_V (Cindex) = Assume_Valid
4795 then
4796 Lo := Determine_Range_Cache_Lo_R (Cindex);
4797 Hi := Determine_Range_Cache_Hi_R (Cindex);
4798 return;
4799 end if;
4801 -- Otherwise, start by finding the bounds of the type of the expression,
4802 -- the value cannot be outside this range (if it is, then we have an
4803 -- overflow situation, which is a separate check, we are talking here
4804 -- only about the expression value).
4806 -- First a check, never try to find the bounds of a generic type, since
4807 -- these bounds are always junk values, and it is only valid to look at
4808 -- the bounds in an instance.
4810 if Is_Generic_Type (Typ) then
4811 OK := False;
4812 return;
4813 end if;
4815 -- First step, change to use base type unless we know the value is valid
4817 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
4818 or else Assume_No_Invalid_Values
4819 or else Assume_Valid
4820 then
4821 null;
4822 else
4823 Typ := Underlying_Type (Base_Type (Typ));
4824 end if;
4826 -- Retrieve the base type. Handle the case where the base type is a
4827 -- private type.
4829 Btyp := Base_Type (Typ);
4831 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
4832 Btyp := Full_View (Btyp);
4833 end if;
4835 -- We use the actual bound unless it is dynamic, in which case use the
4836 -- corresponding base type bound if possible. If we can't get a bound
4837 -- then we figure we can't determine the range (a peculiar case, that
4838 -- perhaps cannot happen, but there is no point in bombing in this
4839 -- optimization circuit).
4841 -- First the low bound
4843 Bound := Type_Low_Bound (Typ);
4845 if Compile_Time_Known_Value (Bound) then
4846 Lo := Expr_Value_R (Bound);
4848 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
4849 Lo := Expr_Value_R (Type_Low_Bound (Btyp));
4851 else
4852 OK := False;
4853 return;
4854 end if;
4856 -- Now the high bound
4858 Bound := Type_High_Bound (Typ);
4860 -- We need the high bound of the base type later on, and this should
4861 -- always be compile time known. Again, it is not clear that this
4862 -- can ever be false, but no point in bombing.
4864 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
4865 Hbound := Expr_Value_R (Type_High_Bound (Btyp));
4866 Hi := Hbound;
4868 else
4869 OK := False;
4870 return;
4871 end if;
4873 -- If we have a static subtype, then that may have a tighter bound so
4874 -- use the upper bound of the subtype instead in this case.
4876 if Compile_Time_Known_Value (Bound) then
4877 Hi := Expr_Value_R (Bound);
4878 end if;
4880 -- We may be able to refine this value in certain situations. If any
4881 -- refinement is possible, then Lor and Hir are set to possibly tighter
4882 -- bounds, and OK1 is set to True.
4884 case Nkind (N) is
4886 -- For unary plus, result is limited by range of operand
4888 when N_Op_Plus =>
4889 Determine_Range_R
4890 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
4892 -- For unary minus, determine range of operand, and negate it
4894 when N_Op_Minus =>
4895 Determine_Range_R
4896 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4898 if OK1 then
4899 Lor := -Hi_Right;
4900 Hir := -Lo_Right;
4901 end if;
4903 -- For binary addition, get range of each operand and do the
4904 -- addition to get the result range.
4906 when N_Op_Add =>
4907 if OK_Operands then
4908 Lor := Round_Machine (Lo_Left + Lo_Right);
4909 Hir := Round_Machine (Hi_Left + Hi_Right);
4910 end if;
4912 -- For binary subtraction, get range of each operand and do the worst
4913 -- case subtraction to get the result range.
4915 when N_Op_Subtract =>
4916 if OK_Operands then
4917 Lor := Round_Machine (Lo_Left - Hi_Right);
4918 Hir := Round_Machine (Hi_Left - Lo_Right);
4919 end if;
4921 -- For multiplication, get range of each operand and do the
4922 -- four multiplications to get the result range.
4924 when N_Op_Multiply =>
4925 if OK_Operands then
4926 declare
4927 M1 : constant Ureal := Round_Machine (Lo_Left * Lo_Right);
4928 M2 : constant Ureal := Round_Machine (Lo_Left * Hi_Right);
4929 M3 : constant Ureal := Round_Machine (Hi_Left * Lo_Right);
4930 M4 : constant Ureal := Round_Machine (Hi_Left * Hi_Right);
4931 begin
4932 Lor := UR_Min (UR_Min (M1, M2), UR_Min (M3, M4));
4933 Hir := UR_Max (UR_Max (M1, M2), UR_Max (M3, M4));
4934 end;
4935 end if;
4937 -- For division, consider separately the cases where the right
4938 -- operand is positive or negative. Otherwise, the right operand
4939 -- can be arbitrarily close to zero, so the result is likely to
4940 -- be unbounded in one direction, do not attempt to compute it.
4942 when N_Op_Divide =>
4943 if OK_Operands then
4945 -- Right operand is positive
4947 if Lo_Right > Ureal_0 then
4949 -- If the low bound of the left operand is negative, obtain
4950 -- the overall low bound by dividing it by the smallest
4951 -- value of the right operand, and otherwise by the largest
4952 -- value of the right operand.
4954 if Lo_Left < Ureal_0 then
4955 Lor := Round_Machine (Lo_Left / Lo_Right);
4956 else
4957 Lor := Round_Machine (Lo_Left / Hi_Right);
4958 end if;
4960 -- If the high bound of the left operand is negative, obtain
4961 -- the overall high bound by dividing it by the largest
4962 -- value of the right operand, and otherwise by the
4963 -- smallest value of the right operand.
4965 if Hi_Left < Ureal_0 then
4966 Hir := Round_Machine (Hi_Left / Hi_Right);
4967 else
4968 Hir := Round_Machine (Hi_Left / Lo_Right);
4969 end if;
4971 -- Right operand is negative
4973 elsif Hi_Right < Ureal_0 then
4975 -- If the low bound of the left operand is negative, obtain
4976 -- the overall low bound by dividing it by the largest
4977 -- value of the right operand, and otherwise by the smallest
4978 -- value of the right operand.
4980 if Lo_Left < Ureal_0 then
4981 Lor := Round_Machine (Lo_Left / Hi_Right);
4982 else
4983 Lor := Round_Machine (Lo_Left / Lo_Right);
4984 end if;
4986 -- If the high bound of the left operand is negative, obtain
4987 -- the overall high bound by dividing it by the smallest
4988 -- value of the right operand, and otherwise by the
4989 -- largest value of the right operand.
4991 if Hi_Left < Ureal_0 then
4992 Hir := Round_Machine (Hi_Left / Lo_Right);
4993 else
4994 Hir := Round_Machine (Hi_Left / Hi_Right);
4995 end if;
4997 else
4998 OK1 := False;
4999 end if;
5000 end if;
5002 -- For type conversion from one floating-point type to another, we
5003 -- can refine the range using the converted value.
5005 when N_Type_Conversion =>
5006 Determine_Range_R (Expression (N), OK1, Lor, Hir, Assume_Valid);
5008 -- Nothing special to do for all other expression kinds
5010 when others =>
5011 OK1 := False;
5012 Lor := No_Ureal;
5013 Hir := No_Ureal;
5014 end case;
5016 -- At this stage, if OK1 is true, then we know that the actual result of
5017 -- the computed expression is in the range Lor .. Hir. We can use this
5018 -- to restrict the possible range of results.
5020 if OK1 then
5022 -- If the refined value of the low bound is greater than the type
5023 -- low bound, then reset it to the more restrictive value.
5025 if Lor > Lo then
5026 Lo := Lor;
5027 end if;
5029 -- Similarly, if the refined value of the high bound is less than the
5030 -- value so far, then reset it to the more restrictive value.
5032 if Hir < Hi then
5033 Hi := Hir;
5034 end if;
5035 end if;
5037 -- Set cache entry for future call and we are all done
5039 Determine_Range_Cache_N (Cindex) := N;
5040 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5041 Determine_Range_Cache_Lo_R (Cindex) := Lo;
5042 Determine_Range_Cache_Hi_R (Cindex) := Hi;
5043 return;
5045 -- If any exception occurs, it means that we have some bug in the compiler,
5046 -- possibly triggered by a previous error, or by some unforeseen peculiar
5047 -- occurrence. However, this is only an optimization attempt, so there is
5048 -- really no point in crashing the compiler. Instead we just decide, too
5049 -- bad, we can't figure out a range in this case after all.
5051 exception
5052 when others =>
5054 -- Debug flag K disables this behavior (useful for debugging)
5056 if Debug_Flag_K then
5057 raise;
5058 else
5059 OK := False;
5060 Lo := No_Ureal;
5061 Hi := No_Ureal;
5062 return;
5063 end if;
5064 end Determine_Range_R;
5066 ------------------------------------
5067 -- Discriminant_Checks_Suppressed --
5068 ------------------------------------
5070 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
5071 begin
5072 if Present (E) then
5073 if Is_Unchecked_Union (E) then
5074 return True;
5075 elsif Checks_May_Be_Suppressed (E) then
5076 return Is_Check_Suppressed (E, Discriminant_Check);
5077 end if;
5078 end if;
5080 return Scope_Suppress.Suppress (Discriminant_Check);
5081 end Discriminant_Checks_Suppressed;
5083 --------------------------------
5084 -- Division_Checks_Suppressed --
5085 --------------------------------
5087 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
5088 begin
5089 if Present (E) and then Checks_May_Be_Suppressed (E) then
5090 return Is_Check_Suppressed (E, Division_Check);
5091 else
5092 return Scope_Suppress.Suppress (Division_Check);
5093 end if;
5094 end Division_Checks_Suppressed;
5096 --------------------------------------
5097 -- Duplicated_Tag_Checks_Suppressed --
5098 --------------------------------------
5100 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
5101 begin
5102 if Present (E) and then Checks_May_Be_Suppressed (E) then
5103 return Is_Check_Suppressed (E, Duplicated_Tag_Check);
5104 else
5105 return Scope_Suppress.Suppress (Duplicated_Tag_Check);
5106 end if;
5107 end Duplicated_Tag_Checks_Suppressed;
5109 -----------------------------------
5110 -- Elaboration_Checks_Suppressed --
5111 -----------------------------------
5113 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
5114 begin
5115 -- The complication in this routine is that if we are in the dynamic
5116 -- model of elaboration, we also check All_Checks, since All_Checks
5117 -- does not set Elaboration_Check explicitly.
5119 if Present (E) then
5120 if Kill_Elaboration_Checks (E) then
5121 return True;
5123 elsif Checks_May_Be_Suppressed (E) then
5124 if Is_Check_Suppressed (E, Elaboration_Check) then
5125 return True;
5126 elsif Dynamic_Elaboration_Checks then
5127 return Is_Check_Suppressed (E, All_Checks);
5128 else
5129 return False;
5130 end if;
5131 end if;
5132 end if;
5134 if Scope_Suppress.Suppress (Elaboration_Check) then
5135 return True;
5136 elsif Dynamic_Elaboration_Checks then
5137 return Scope_Suppress.Suppress (All_Checks);
5138 else
5139 return False;
5140 end if;
5141 end Elaboration_Checks_Suppressed;
5143 ---------------------------
5144 -- Enable_Overflow_Check --
5145 ---------------------------
5147 procedure Enable_Overflow_Check (N : Node_Id) is
5148 Typ : constant Entity_Id := Base_Type (Etype (N));
5149 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
5150 Chk : Nat;
5151 OK : Boolean;
5152 Ent : Entity_Id;
5153 Ofs : Uint;
5154 Lo : Uint;
5155 Hi : Uint;
5157 Do_Ovflow_Check : Boolean;
5159 begin
5160 if Debug_Flag_CC then
5161 w ("Enable_Overflow_Check for node ", Int (N));
5162 Write_Str (" Source location = ");
5163 wl (Sloc (N));
5164 pg (Union_Id (N));
5165 end if;
5167 -- No check if overflow checks suppressed for type of node
5169 if Overflow_Checks_Suppressed (Etype (N)) then
5170 return;
5172 -- Nothing to do for unsigned integer types, which do not overflow
5174 elsif Is_Modular_Integer_Type (Typ) then
5175 return;
5176 end if;
5178 -- This is the point at which processing for STRICT mode diverges
5179 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
5180 -- probably more extreme that it needs to be, but what is going on here
5181 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
5182 -- to leave the processing for STRICT mode untouched. There were
5183 -- two reasons for this. First it avoided any incompatible change of
5184 -- behavior. Second, it guaranteed that STRICT mode continued to be
5185 -- legacy reliable.
5187 -- The big difference is that in STRICT mode there is a fair amount of
5188 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
5189 -- know that no check is needed. We skip all that in the two new modes,
5190 -- since really overflow checking happens over a whole subtree, and we
5191 -- do the corresponding optimizations later on when applying the checks.
5193 if Mode in Minimized_Or_Eliminated then
5194 if not (Overflow_Checks_Suppressed (Etype (N)))
5195 and then not (Is_Entity_Name (N)
5196 and then Overflow_Checks_Suppressed (Entity (N)))
5197 then
5198 Activate_Overflow_Check (N);
5199 end if;
5201 if Debug_Flag_CC then
5202 w ("Minimized/Eliminated mode");
5203 end if;
5205 return;
5206 end if;
5208 -- Remainder of processing is for STRICT case, and is unchanged from
5209 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
5211 -- Nothing to do if the range of the result is known OK. We skip this
5212 -- for conversions, since the caller already did the check, and in any
5213 -- case the condition for deleting the check for a type conversion is
5214 -- different.
5216 if Nkind (N) /= N_Type_Conversion then
5217 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
5219 -- Note in the test below that we assume that the range is not OK
5220 -- if a bound of the range is equal to that of the type. That's not
5221 -- quite accurate but we do this for the following reasons:
5223 -- a) The way that Determine_Range works, it will typically report
5224 -- the bounds of the value as being equal to the bounds of the
5225 -- type, because it either can't tell anything more precise, or
5226 -- does not think it is worth the effort to be more precise.
5228 -- b) It is very unusual to have a situation in which this would
5229 -- generate an unnecessary overflow check (an example would be
5230 -- a subtype with a range 0 .. Integer'Last - 1 to which the
5231 -- literal value one is added).
5233 -- c) The alternative is a lot of special casing in this routine
5234 -- which would partially duplicate Determine_Range processing.
5236 if OK then
5237 Do_Ovflow_Check := True;
5239 -- Note that the following checks are quite deliberately > and <
5240 -- rather than >= and <= as explained above.
5242 if Lo > Expr_Value (Type_Low_Bound (Typ))
5243 and then
5244 Hi < Expr_Value (Type_High_Bound (Typ))
5245 then
5246 Do_Ovflow_Check := False;
5248 -- Despite the comments above, it is worth dealing specially with
5249 -- division specially. The only case where integer division can
5250 -- overflow is (largest negative number) / (-1). So we will do
5251 -- an extra range analysis to see if this is possible.
5253 elsif Nkind (N) = N_Op_Divide then
5254 Determine_Range
5255 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5257 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
5258 Do_Ovflow_Check := False;
5260 else
5261 Determine_Range
5262 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5264 if OK and then (Lo > Uint_Minus_1
5265 or else
5266 Hi < Uint_Minus_1)
5267 then
5268 Do_Ovflow_Check := False;
5269 end if;
5270 end if;
5271 end if;
5273 -- If no overflow check required, we are done
5275 if not Do_Ovflow_Check then
5276 if Debug_Flag_CC then
5277 w ("No overflow check required");
5278 end if;
5280 return;
5281 end if;
5282 end if;
5283 end if;
5285 -- If not in optimizing mode, set flag and we are done. We are also done
5286 -- (and just set the flag) if the type is not a discrete type, since it
5287 -- is not worth the effort to eliminate checks for other than discrete
5288 -- types. In addition, we take this same path if we have stored the
5289 -- maximum number of checks possible already (a very unlikely situation,
5290 -- but we do not want to blow up).
5292 if Optimization_Level = 0
5293 or else not Is_Discrete_Type (Etype (N))
5294 or else Num_Saved_Checks = Saved_Checks'Last
5295 then
5296 Activate_Overflow_Check (N);
5298 if Debug_Flag_CC then
5299 w ("Optimization off");
5300 end if;
5302 return;
5303 end if;
5305 -- Otherwise evaluate and check the expression
5307 Find_Check
5308 (Expr => N,
5309 Check_Type => 'O',
5310 Target_Type => Empty,
5311 Entry_OK => OK,
5312 Check_Num => Chk,
5313 Ent => Ent,
5314 Ofs => Ofs);
5316 if Debug_Flag_CC then
5317 w ("Called Find_Check");
5318 w (" OK = ", OK);
5320 if OK then
5321 w (" Check_Num = ", Chk);
5322 w (" Ent = ", Int (Ent));
5323 Write_Str (" Ofs = ");
5324 pid (Ofs);
5325 end if;
5326 end if;
5328 -- If check is not of form to optimize, then set flag and we are done
5330 if not OK then
5331 Activate_Overflow_Check (N);
5332 return;
5333 end if;
5335 -- If check is already performed, then return without setting flag
5337 if Chk /= 0 then
5338 if Debug_Flag_CC then
5339 w ("Check suppressed!");
5340 end if;
5342 return;
5343 end if;
5345 -- Here we will make a new entry for the new check
5347 Activate_Overflow_Check (N);
5348 Num_Saved_Checks := Num_Saved_Checks + 1;
5349 Saved_Checks (Num_Saved_Checks) :=
5350 (Killed => False,
5351 Entity => Ent,
5352 Offset => Ofs,
5353 Check_Type => 'O',
5354 Target_Type => Empty);
5356 if Debug_Flag_CC then
5357 w ("Make new entry, check number = ", Num_Saved_Checks);
5358 w (" Entity = ", Int (Ent));
5359 Write_Str (" Offset = ");
5360 pid (Ofs);
5361 w (" Check_Type = O");
5362 w (" Target_Type = Empty");
5363 end if;
5365 -- If we get an exception, then something went wrong, probably because of
5366 -- an error in the structure of the tree due to an incorrect program. Or
5367 -- it may be a bug in the optimization circuit. In either case the safest
5368 -- thing is simply to set the check flag unconditionally.
5370 exception
5371 when others =>
5372 Activate_Overflow_Check (N);
5374 if Debug_Flag_CC then
5375 w (" exception occurred, overflow flag set");
5376 end if;
5378 return;
5379 end Enable_Overflow_Check;
5381 ------------------------
5382 -- Enable_Range_Check --
5383 ------------------------
5385 procedure Enable_Range_Check (N : Node_Id) is
5386 Chk : Nat;
5387 OK : Boolean;
5388 Ent : Entity_Id;
5389 Ofs : Uint;
5390 Ttyp : Entity_Id;
5391 P : Node_Id;
5393 begin
5394 -- Return if unchecked type conversion with range check killed. In this
5395 -- case we never set the flag (that's what Kill_Range_Check is about).
5397 if Nkind (N) = N_Unchecked_Type_Conversion
5398 and then Kill_Range_Check (N)
5399 then
5400 return;
5401 end if;
5403 -- Do not set range check flag if parent is assignment statement or
5404 -- object declaration with Suppress_Assignment_Checks flag set
5406 if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
5407 and then Suppress_Assignment_Checks (Parent (N))
5408 then
5409 return;
5410 end if;
5412 -- Check for various cases where we should suppress the range check
5414 -- No check if range checks suppressed for type of node
5416 if Present (Etype (N)) and then Range_Checks_Suppressed (Etype (N)) then
5417 return;
5419 -- No check if node is an entity name, and range checks are suppressed
5420 -- for this entity, or for the type of this entity.
5422 elsif Is_Entity_Name (N)
5423 and then (Range_Checks_Suppressed (Entity (N))
5424 or else Range_Checks_Suppressed (Etype (Entity (N))))
5425 then
5426 return;
5428 -- No checks if index of array, and index checks are suppressed for
5429 -- the array object or the type of the array.
5431 elsif Nkind (Parent (N)) = N_Indexed_Component then
5432 declare
5433 Pref : constant Node_Id := Prefix (Parent (N));
5434 begin
5435 if Is_Entity_Name (Pref)
5436 and then Index_Checks_Suppressed (Entity (Pref))
5437 then
5438 return;
5439 elsif Index_Checks_Suppressed (Etype (Pref)) then
5440 return;
5441 end if;
5442 end;
5443 end if;
5445 -- Debug trace output
5447 if Debug_Flag_CC then
5448 w ("Enable_Range_Check for node ", Int (N));
5449 Write_Str (" Source location = ");
5450 wl (Sloc (N));
5451 pg (Union_Id (N));
5452 end if;
5454 -- If not in optimizing mode, set flag and we are done. We are also done
5455 -- (and just set the flag) if the type is not a discrete type, since it
5456 -- is not worth the effort to eliminate checks for other than discrete
5457 -- types. In addition, we take this same path if we have stored the
5458 -- maximum number of checks possible already (a very unlikely situation,
5459 -- but we do not want to blow up).
5461 if Optimization_Level = 0
5462 or else No (Etype (N))
5463 or else not Is_Discrete_Type (Etype (N))
5464 or else Num_Saved_Checks = Saved_Checks'Last
5465 then
5466 Activate_Range_Check (N);
5468 if Debug_Flag_CC then
5469 w ("Optimization off");
5470 end if;
5472 return;
5473 end if;
5475 -- Otherwise find out the target type
5477 P := Parent (N);
5479 -- For assignment, use left side subtype
5481 if Nkind (P) = N_Assignment_Statement
5482 and then Expression (P) = N
5483 then
5484 Ttyp := Etype (Name (P));
5486 -- For indexed component, use subscript subtype
5488 elsif Nkind (P) = N_Indexed_Component then
5489 declare
5490 Atyp : Entity_Id;
5491 Indx : Node_Id;
5492 Subs : Node_Id;
5494 begin
5495 Atyp := Etype (Prefix (P));
5497 if Is_Access_Type (Atyp) then
5498 Atyp := Designated_Type (Atyp);
5500 -- If the prefix is an access to an unconstrained array,
5501 -- perform check unconditionally: it depends on the bounds of
5502 -- an object and we cannot currently recognize whether the test
5503 -- may be redundant.
5505 if not Is_Constrained (Atyp) then
5506 Activate_Range_Check (N);
5507 return;
5508 end if;
5510 -- Ditto if the prefix is an explicit dereference whose designated
5511 -- type is unconstrained.
5513 elsif Nkind (Prefix (P)) = N_Explicit_Dereference
5514 and then not Is_Constrained (Atyp)
5515 then
5516 Activate_Range_Check (N);
5517 return;
5518 end if;
5520 Indx := First_Index (Atyp);
5521 Subs := First (Expressions (P));
5522 loop
5523 if Subs = N then
5524 Ttyp := Etype (Indx);
5525 exit;
5526 end if;
5528 Next_Index (Indx);
5529 Next (Subs);
5530 end loop;
5531 end;
5533 -- For now, ignore all other cases, they are not so interesting
5535 else
5536 if Debug_Flag_CC then
5537 w (" target type not found, flag set");
5538 end if;
5540 Activate_Range_Check (N);
5541 return;
5542 end if;
5544 -- Evaluate and check the expression
5546 Find_Check
5547 (Expr => N,
5548 Check_Type => 'R',
5549 Target_Type => Ttyp,
5550 Entry_OK => OK,
5551 Check_Num => Chk,
5552 Ent => Ent,
5553 Ofs => Ofs);
5555 if Debug_Flag_CC then
5556 w ("Called Find_Check");
5557 w ("Target_Typ = ", Int (Ttyp));
5558 w (" OK = ", OK);
5560 if OK then
5561 w (" Check_Num = ", Chk);
5562 w (" Ent = ", Int (Ent));
5563 Write_Str (" Ofs = ");
5564 pid (Ofs);
5565 end if;
5566 end if;
5568 -- If check is not of form to optimize, then set flag and we are done
5570 if not OK then
5571 if Debug_Flag_CC then
5572 w (" expression not of optimizable type, flag set");
5573 end if;
5575 Activate_Range_Check (N);
5576 return;
5577 end if;
5579 -- If check is already performed, then return without setting flag
5581 if Chk /= 0 then
5582 if Debug_Flag_CC then
5583 w ("Check suppressed!");
5584 end if;
5586 return;
5587 end if;
5589 -- Here we will make a new entry for the new check
5591 Activate_Range_Check (N);
5592 Num_Saved_Checks := Num_Saved_Checks + 1;
5593 Saved_Checks (Num_Saved_Checks) :=
5594 (Killed => False,
5595 Entity => Ent,
5596 Offset => Ofs,
5597 Check_Type => 'R',
5598 Target_Type => Ttyp);
5600 if Debug_Flag_CC then
5601 w ("Make new entry, check number = ", Num_Saved_Checks);
5602 w (" Entity = ", Int (Ent));
5603 Write_Str (" Offset = ");
5604 pid (Ofs);
5605 w (" Check_Type = R");
5606 w (" Target_Type = ", Int (Ttyp));
5607 pg (Union_Id (Ttyp));
5608 end if;
5610 -- If we get an exception, then something went wrong, probably because of
5611 -- an error in the structure of the tree due to an incorrect program. Or
5612 -- it may be a bug in the optimization circuit. In either case the safest
5613 -- thing is simply to set the check flag unconditionally.
5615 exception
5616 when others =>
5617 Activate_Range_Check (N);
5619 if Debug_Flag_CC then
5620 w (" exception occurred, range flag set");
5621 end if;
5623 return;
5624 end Enable_Range_Check;
5626 ------------------
5627 -- Ensure_Valid --
5628 ------------------
5630 procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
5631 Typ : constant Entity_Id := Etype (Expr);
5633 begin
5634 -- Ignore call if we are not doing any validity checking
5636 if not Validity_Checks_On then
5637 return;
5639 -- Ignore call if range or validity checks suppressed on entity or type
5641 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
5642 return;
5644 -- No check required if expression is from the expander, we assume the
5645 -- expander will generate whatever checks are needed. Note that this is
5646 -- not just an optimization, it avoids infinite recursions.
5648 -- Unchecked conversions must be checked, unless they are initialized
5649 -- scalar values, as in a component assignment in an init proc.
5651 -- In addition, we force a check if Force_Validity_Checks is set
5653 elsif not Comes_From_Source (Expr)
5654 and then not Force_Validity_Checks
5655 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
5656 or else Kill_Range_Check (Expr))
5657 then
5658 return;
5660 -- No check required if expression is known to have valid value
5662 elsif Expr_Known_Valid (Expr) then
5663 return;
5665 -- Ignore case of enumeration with holes where the flag is set not to
5666 -- worry about holes, since no special validity check is needed
5668 elsif Is_Enumeration_Type (Typ)
5669 and then Has_Non_Standard_Rep (Typ)
5670 and then Holes_OK
5671 then
5672 return;
5674 -- No check required on the left-hand side of an assignment
5676 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
5677 and then Expr = Name (Parent (Expr))
5678 then
5679 return;
5681 -- No check on a universal real constant. The context will eventually
5682 -- convert it to a machine number for some target type, or report an
5683 -- illegality.
5685 elsif Nkind (Expr) = N_Real_Literal
5686 and then Etype (Expr) = Universal_Real
5687 then
5688 return;
5690 -- If the expression denotes a component of a packed boolean array,
5691 -- no possible check applies. We ignore the old ACATS chestnuts that
5692 -- involve Boolean range True..True.
5694 -- Note: validity checks are generated for expressions that yield a
5695 -- scalar type, when it is possible to create a value that is outside of
5696 -- the type. If this is a one-bit boolean no such value exists. This is
5697 -- an optimization, and it also prevents compiler blowing up during the
5698 -- elaboration of improperly expanded packed array references.
5700 elsif Nkind (Expr) = N_Indexed_Component
5701 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
5702 and then Root_Type (Etype (Expr)) = Standard_Boolean
5703 then
5704 return;
5706 -- For an expression with actions, we want to insert the validity check
5707 -- on the final Expression.
5709 elsif Nkind (Expr) = N_Expression_With_Actions then
5710 Ensure_Valid (Expression (Expr));
5711 return;
5713 -- An annoying special case. If this is an out parameter of a scalar
5714 -- type, then the value is not going to be accessed, therefore it is
5715 -- inappropriate to do any validity check at the call site.
5717 else
5718 -- Only need to worry about scalar types
5720 if Is_Scalar_Type (Typ) then
5721 declare
5722 P : Node_Id;
5723 N : Node_Id;
5724 E : Entity_Id;
5725 F : Entity_Id;
5726 A : Node_Id;
5727 L : List_Id;
5729 begin
5730 -- Find actual argument (which may be a parameter association)
5731 -- and the parent of the actual argument (the call statement)
5733 N := Expr;
5734 P := Parent (Expr);
5736 if Nkind (P) = N_Parameter_Association then
5737 N := P;
5738 P := Parent (N);
5739 end if;
5741 -- Only need to worry if we are argument of a procedure call
5742 -- since functions don't have out parameters. If this is an
5743 -- indirect or dispatching call, get signature from the
5744 -- subprogram type.
5746 if Nkind (P) = N_Procedure_Call_Statement then
5747 L := Parameter_Associations (P);
5749 if Is_Entity_Name (Name (P)) then
5750 E := Entity (Name (P));
5751 else
5752 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
5753 E := Etype (Name (P));
5754 end if;
5756 -- Only need to worry if there are indeed actuals, and if
5757 -- this could be a procedure call, otherwise we cannot get a
5758 -- match (either we are not an argument, or the mode of the
5759 -- formal is not OUT). This test also filters out the
5760 -- generic case.
5762 if Is_Non_Empty_List (L) and then Is_Subprogram (E) then
5764 -- This is the loop through parameters, looking for an
5765 -- OUT parameter for which we are the argument.
5767 F := First_Formal (E);
5768 A := First (L);
5769 while Present (F) loop
5770 if Ekind (F) = E_Out_Parameter and then A = N then
5771 return;
5772 end if;
5774 Next_Formal (F);
5775 Next (A);
5776 end loop;
5777 end if;
5778 end if;
5779 end;
5780 end if;
5781 end if;
5783 -- If this is a boolean expression, only its elementary operands need
5784 -- checking: if they are valid, a boolean or short-circuit operation
5785 -- with them will be valid as well.
5787 if Base_Type (Typ) = Standard_Boolean
5788 and then
5789 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
5790 then
5791 return;
5792 end if;
5794 -- If we fall through, a validity check is required
5796 Insert_Valid_Check (Expr);
5798 if Is_Entity_Name (Expr)
5799 and then Safe_To_Capture_Value (Expr, Entity (Expr))
5800 then
5801 Set_Is_Known_Valid (Entity (Expr));
5802 end if;
5803 end Ensure_Valid;
5805 ----------------------
5806 -- Expr_Known_Valid --
5807 ----------------------
5809 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
5810 Typ : constant Entity_Id := Etype (Expr);
5812 begin
5813 -- Non-scalar types are always considered valid, since they never give
5814 -- rise to the issues of erroneous or bounded error behavior that are
5815 -- the concern. In formal reference manual terms the notion of validity
5816 -- only applies to scalar types. Note that even when packed arrays are
5817 -- represented using modular types, they are still arrays semantically,
5818 -- so they are also always valid (in particular, the unused bits can be
5819 -- random rubbish without affecting the validity of the array value).
5821 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Impl_Type (Typ) then
5822 return True;
5824 -- If no validity checking, then everything is considered valid
5826 elsif not Validity_Checks_On then
5827 return True;
5829 -- Floating-point types are considered valid unless floating-point
5830 -- validity checks have been specifically turned on.
5832 elsif Is_Floating_Point_Type (Typ)
5833 and then not Validity_Check_Floating_Point
5834 then
5835 return True;
5837 -- If the expression is the value of an object that is known to be
5838 -- valid, then clearly the expression value itself is valid.
5840 elsif Is_Entity_Name (Expr)
5841 and then Is_Known_Valid (Entity (Expr))
5843 -- Exclude volatile variables
5845 and then not Treat_As_Volatile (Entity (Expr))
5846 then
5847 return True;
5849 -- References to discriminants are always considered valid. The value
5850 -- of a discriminant gets checked when the object is built. Within the
5851 -- record, we consider it valid, and it is important to do so, since
5852 -- otherwise we can try to generate bogus validity checks which
5853 -- reference discriminants out of scope. Discriminants of concurrent
5854 -- types are excluded for the same reason.
5856 elsif Is_Entity_Name (Expr)
5857 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
5858 then
5859 return True;
5861 -- If the type is one for which all values are known valid, then we are
5862 -- sure that the value is valid except in the slightly odd case where
5863 -- the expression is a reference to a variable whose size has been
5864 -- explicitly set to a value greater than the object size.
5866 elsif Is_Known_Valid (Typ) then
5867 if Is_Entity_Name (Expr)
5868 and then Ekind (Entity (Expr)) = E_Variable
5869 and then Esize (Entity (Expr)) > Esize (Typ)
5870 then
5871 return False;
5872 else
5873 return True;
5874 end if;
5876 -- Integer and character literals always have valid values, where
5877 -- appropriate these will be range checked in any case.
5879 elsif Nkind_In (Expr, N_Integer_Literal, N_Character_Literal) then
5880 return True;
5882 -- Real literals are assumed to be valid in VM targets
5884 elsif VM_Target /= No_VM and then Nkind (Expr) = N_Real_Literal then
5885 return True;
5887 -- If we have a type conversion or a qualification of a known valid
5888 -- value, then the result will always be valid.
5890 elsif Nkind_In (Expr, N_Type_Conversion, N_Qualified_Expression) then
5891 return Expr_Known_Valid (Expression (Expr));
5893 -- Case of expression is a non-floating-point operator. In this case we
5894 -- can assume the result is valid the generated code for the operator
5895 -- will include whatever checks are needed (e.g. range checks) to ensure
5896 -- validity. This assumption does not hold for the floating-point case,
5897 -- since floating-point operators can generate Infinite or NaN results
5898 -- which are considered invalid.
5900 -- Historical note: in older versions, the exemption of floating-point
5901 -- types from this assumption was done only in cases where the parent
5902 -- was an assignment, function call or parameter association. Presumably
5903 -- the idea was that in other contexts, the result would be checked
5904 -- elsewhere, but this list of cases was missing tests (at least the
5905 -- N_Object_Declaration case, as shown by a reported missing validity
5906 -- check), and it is not clear why function calls but not procedure
5907 -- calls were tested for. It really seems more accurate and much
5908 -- safer to recognize that expressions which are the result of a
5909 -- floating-point operator can never be assumed to be valid.
5911 elsif Nkind (Expr) in N_Op and then not Is_Floating_Point_Type (Typ) then
5912 return True;
5914 -- The result of a membership test is always valid, since it is true or
5915 -- false, there are no other possibilities.
5917 elsif Nkind (Expr) in N_Membership_Test then
5918 return True;
5920 -- For all other cases, we do not know the expression is valid
5922 else
5923 return False;
5924 end if;
5925 end Expr_Known_Valid;
5927 ----------------
5928 -- Find_Check --
5929 ----------------
5931 procedure Find_Check
5932 (Expr : Node_Id;
5933 Check_Type : Character;
5934 Target_Type : Entity_Id;
5935 Entry_OK : out Boolean;
5936 Check_Num : out Nat;
5937 Ent : out Entity_Id;
5938 Ofs : out Uint)
5940 function Within_Range_Of
5941 (Target_Type : Entity_Id;
5942 Check_Type : Entity_Id) return Boolean;
5943 -- Given a requirement for checking a range against Target_Type, and
5944 -- and a range Check_Type against which a check has already been made,
5945 -- determines if the check against check type is sufficient to ensure
5946 -- that no check against Target_Type is required.
5948 ---------------------
5949 -- Within_Range_Of --
5950 ---------------------
5952 function Within_Range_Of
5953 (Target_Type : Entity_Id;
5954 Check_Type : Entity_Id) return Boolean
5956 begin
5957 if Target_Type = Check_Type then
5958 return True;
5960 else
5961 declare
5962 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
5963 Thi : constant Node_Id := Type_High_Bound (Target_Type);
5964 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
5965 Chi : constant Node_Id := Type_High_Bound (Check_Type);
5967 begin
5968 if (Tlo = Clo
5969 or else (Compile_Time_Known_Value (Tlo)
5970 and then
5971 Compile_Time_Known_Value (Clo)
5972 and then
5973 Expr_Value (Clo) >= Expr_Value (Tlo)))
5974 and then
5975 (Thi = Chi
5976 or else (Compile_Time_Known_Value (Thi)
5977 and then
5978 Compile_Time_Known_Value (Chi)
5979 and then
5980 Expr_Value (Chi) <= Expr_Value (Clo)))
5981 then
5982 return True;
5983 else
5984 return False;
5985 end if;
5986 end;
5987 end if;
5988 end Within_Range_Of;
5990 -- Start of processing for Find_Check
5992 begin
5993 -- Establish default, in case no entry is found
5995 Check_Num := 0;
5997 -- Case of expression is simple entity reference
5999 if Is_Entity_Name (Expr) then
6000 Ent := Entity (Expr);
6001 Ofs := Uint_0;
6003 -- Case of expression is entity + known constant
6005 elsif Nkind (Expr) = N_Op_Add
6006 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6007 and then Is_Entity_Name (Left_Opnd (Expr))
6008 then
6009 Ent := Entity (Left_Opnd (Expr));
6010 Ofs := Expr_Value (Right_Opnd (Expr));
6012 -- Case of expression is entity - known constant
6014 elsif Nkind (Expr) = N_Op_Subtract
6015 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6016 and then Is_Entity_Name (Left_Opnd (Expr))
6017 then
6018 Ent := Entity (Left_Opnd (Expr));
6019 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
6021 -- Any other expression is not of the right form
6023 else
6024 Ent := Empty;
6025 Ofs := Uint_0;
6026 Entry_OK := False;
6027 return;
6028 end if;
6030 -- Come here with expression of appropriate form, check if entity is an
6031 -- appropriate one for our purposes.
6033 if (Ekind (Ent) = E_Variable
6034 or else Is_Constant_Object (Ent))
6035 and then not Is_Library_Level_Entity (Ent)
6036 then
6037 Entry_OK := True;
6038 else
6039 Entry_OK := False;
6040 return;
6041 end if;
6043 -- See if there is matching check already
6045 for J in reverse 1 .. Num_Saved_Checks loop
6046 declare
6047 SC : Saved_Check renames Saved_Checks (J);
6048 begin
6049 if SC.Killed = False
6050 and then SC.Entity = Ent
6051 and then SC.Offset = Ofs
6052 and then SC.Check_Type = Check_Type
6053 and then Within_Range_Of (Target_Type, SC.Target_Type)
6054 then
6055 Check_Num := J;
6056 return;
6057 end if;
6058 end;
6059 end loop;
6061 -- If we fall through entry was not found
6063 return;
6064 end Find_Check;
6066 ---------------------------------
6067 -- Generate_Discriminant_Check --
6068 ---------------------------------
6070 -- Note: the code for this procedure is derived from the
6071 -- Emit_Discriminant_Check Routine in trans.c.
6073 procedure Generate_Discriminant_Check (N : Node_Id) is
6074 Loc : constant Source_Ptr := Sloc (N);
6075 Pref : constant Node_Id := Prefix (N);
6076 Sel : constant Node_Id := Selector_Name (N);
6078 Orig_Comp : constant Entity_Id :=
6079 Original_Record_Component (Entity (Sel));
6080 -- The original component to be checked
6082 Discr_Fct : constant Entity_Id :=
6083 Discriminant_Checking_Func (Orig_Comp);
6084 -- The discriminant checking function
6086 Discr : Entity_Id;
6087 -- One discriminant to be checked in the type
6089 Real_Discr : Entity_Id;
6090 -- Actual discriminant in the call
6092 Pref_Type : Entity_Id;
6093 -- Type of relevant prefix (ignoring private/access stuff)
6095 Args : List_Id;
6096 -- List of arguments for function call
6098 Formal : Entity_Id;
6099 -- Keep track of the formal corresponding to the actual we build for
6100 -- each discriminant, in order to be able to perform the necessary type
6101 -- conversions.
6103 Scomp : Node_Id;
6104 -- Selected component reference for checking function argument
6106 begin
6107 Pref_Type := Etype (Pref);
6109 -- Force evaluation of the prefix, so that it does not get evaluated
6110 -- twice (once for the check, once for the actual reference). Such a
6111 -- double evaluation is always a potential source of inefficiency, and
6112 -- is functionally incorrect in the volatile case, or when the prefix
6113 -- may have side-effects. A non-volatile entity or a component of a
6114 -- non-volatile entity requires no evaluation.
6116 if Is_Entity_Name (Pref) then
6117 if Treat_As_Volatile (Entity (Pref)) then
6118 Force_Evaluation (Pref, Name_Req => True);
6119 end if;
6121 elsif Treat_As_Volatile (Etype (Pref)) then
6122 Force_Evaluation (Pref, Name_Req => True);
6124 elsif Nkind (Pref) = N_Selected_Component
6125 and then Is_Entity_Name (Prefix (Pref))
6126 then
6127 null;
6129 else
6130 Force_Evaluation (Pref, Name_Req => True);
6131 end if;
6133 -- For a tagged type, use the scope of the original component to
6134 -- obtain the type, because ???
6136 if Is_Tagged_Type (Scope (Orig_Comp)) then
6137 Pref_Type := Scope (Orig_Comp);
6139 -- For an untagged derived type, use the discriminants of the parent
6140 -- which have been renamed in the derivation, possibly by a one-to-many
6141 -- discriminant constraint. For untagged type, initially get the Etype
6142 -- of the prefix
6144 else
6145 if Is_Derived_Type (Pref_Type)
6146 and then Number_Discriminants (Pref_Type) /=
6147 Number_Discriminants (Etype (Base_Type (Pref_Type)))
6148 then
6149 Pref_Type := Etype (Base_Type (Pref_Type));
6150 end if;
6151 end if;
6153 -- We definitely should have a checking function, This routine should
6154 -- not be called if no discriminant checking function is present.
6156 pragma Assert (Present (Discr_Fct));
6158 -- Create the list of the actual parameters for the call. This list
6159 -- is the list of the discriminant fields of the record expression to
6160 -- be discriminant checked.
6162 Args := New_List;
6163 Formal := First_Formal (Discr_Fct);
6164 Discr := First_Discriminant (Pref_Type);
6165 while Present (Discr) loop
6167 -- If we have a corresponding discriminant field, and a parent
6168 -- subtype is present, then we want to use the corresponding
6169 -- discriminant since this is the one with the useful value.
6171 if Present (Corresponding_Discriminant (Discr))
6172 and then Ekind (Pref_Type) = E_Record_Type
6173 and then Present (Parent_Subtype (Pref_Type))
6174 then
6175 Real_Discr := Corresponding_Discriminant (Discr);
6176 else
6177 Real_Discr := Discr;
6178 end if;
6180 -- Construct the reference to the discriminant
6182 Scomp :=
6183 Make_Selected_Component (Loc,
6184 Prefix =>
6185 Unchecked_Convert_To (Pref_Type,
6186 Duplicate_Subexpr (Pref)),
6187 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
6189 -- Manually analyze and resolve this selected component. We really
6190 -- want it just as it appears above, and do not want the expander
6191 -- playing discriminal games etc with this reference. Then we append
6192 -- the argument to the list we are gathering.
6194 Set_Etype (Scomp, Etype (Real_Discr));
6195 Set_Analyzed (Scomp, True);
6196 Append_To (Args, Convert_To (Etype (Formal), Scomp));
6198 Next_Formal_With_Extras (Formal);
6199 Next_Discriminant (Discr);
6200 end loop;
6202 -- Now build and insert the call
6204 Insert_Action (N,
6205 Make_Raise_Constraint_Error (Loc,
6206 Condition =>
6207 Make_Function_Call (Loc,
6208 Name => New_Occurrence_Of (Discr_Fct, Loc),
6209 Parameter_Associations => Args),
6210 Reason => CE_Discriminant_Check_Failed));
6211 end Generate_Discriminant_Check;
6213 ---------------------------
6214 -- Generate_Index_Checks --
6215 ---------------------------
6217 procedure Generate_Index_Checks (N : Node_Id) is
6219 function Entity_Of_Prefix return Entity_Id;
6220 -- Returns the entity of the prefix of N (or Empty if not found)
6222 ----------------------
6223 -- Entity_Of_Prefix --
6224 ----------------------
6226 function Entity_Of_Prefix return Entity_Id is
6227 P : Node_Id;
6229 begin
6230 P := Prefix (N);
6231 while not Is_Entity_Name (P) loop
6232 if not Nkind_In (P, N_Selected_Component,
6233 N_Indexed_Component)
6234 then
6235 return Empty;
6236 end if;
6238 P := Prefix (P);
6239 end loop;
6241 return Entity (P);
6242 end Entity_Of_Prefix;
6244 -- Local variables
6246 Loc : constant Source_Ptr := Sloc (N);
6247 A : constant Node_Id := Prefix (N);
6248 A_Ent : constant Entity_Id := Entity_Of_Prefix;
6249 Sub : Node_Id;
6251 -- Start of processing for Generate_Index_Checks
6253 begin
6254 -- Ignore call if the prefix is not an array since we have a serious
6255 -- error in the sources. Ignore it also if index checks are suppressed
6256 -- for array object or type.
6258 if not Is_Array_Type (Etype (A))
6259 or else (Present (A_Ent) and then Index_Checks_Suppressed (A_Ent))
6260 or else Index_Checks_Suppressed (Etype (A))
6261 then
6262 return;
6264 -- The indexed component we are dealing with contains 'Loop_Entry in its
6265 -- prefix. This case arises when analysis has determined that constructs
6266 -- such as
6268 -- Prefix'Loop_Entry (Expr)
6269 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
6271 -- require rewriting for error detection purposes. A side effect of this
6272 -- action is the generation of index checks that mention 'Loop_Entry.
6273 -- Delay the generation of the check until 'Loop_Entry has been properly
6274 -- expanded. This is done in Expand_Loop_Entry_Attributes.
6276 elsif Nkind (Prefix (N)) = N_Attribute_Reference
6277 and then Attribute_Name (Prefix (N)) = Name_Loop_Entry
6278 then
6279 return;
6280 end if;
6282 -- Generate a raise of constraint error with the appropriate reason and
6283 -- a condition of the form:
6285 -- Base_Type (Sub) not in Array'Range (Subscript)
6287 -- Note that the reason we generate the conversion to the base type here
6288 -- is that we definitely want the range check to take place, even if it
6289 -- looks like the subtype is OK. Optimization considerations that allow
6290 -- us to omit the check have already been taken into account in the
6291 -- setting of the Do_Range_Check flag earlier on.
6293 Sub := First (Expressions (N));
6295 -- Handle string literals
6297 if Ekind (Etype (A)) = E_String_Literal_Subtype then
6298 if Do_Range_Check (Sub) then
6299 Set_Do_Range_Check (Sub, False);
6301 -- For string literals we obtain the bounds of the string from the
6302 -- associated subtype.
6304 Insert_Action (N,
6305 Make_Raise_Constraint_Error (Loc,
6306 Condition =>
6307 Make_Not_In (Loc,
6308 Left_Opnd =>
6309 Convert_To (Base_Type (Etype (Sub)),
6310 Duplicate_Subexpr_Move_Checks (Sub)),
6311 Right_Opnd =>
6312 Make_Attribute_Reference (Loc,
6313 Prefix => New_Occurrence_Of (Etype (A), Loc),
6314 Attribute_Name => Name_Range)),
6315 Reason => CE_Index_Check_Failed));
6316 end if;
6318 -- General case
6320 else
6321 declare
6322 A_Idx : Node_Id := Empty;
6323 A_Range : Node_Id;
6324 Ind : Nat;
6325 Num : List_Id;
6326 Range_N : Node_Id;
6328 begin
6329 A_Idx := First_Index (Etype (A));
6330 Ind := 1;
6331 while Present (Sub) loop
6332 if Do_Range_Check (Sub) then
6333 Set_Do_Range_Check (Sub, False);
6335 -- Force evaluation except for the case of a simple name of
6336 -- a non-volatile entity.
6338 if not Is_Entity_Name (Sub)
6339 or else Treat_As_Volatile (Entity (Sub))
6340 then
6341 Force_Evaluation (Sub);
6342 end if;
6344 if Nkind (A_Idx) = N_Range then
6345 A_Range := A_Idx;
6347 elsif Nkind (A_Idx) = N_Identifier
6348 or else Nkind (A_Idx) = N_Expanded_Name
6349 then
6350 A_Range := Scalar_Range (Entity (A_Idx));
6352 else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
6353 A_Range := Range_Expression (Constraint (A_Idx));
6354 end if;
6356 -- For array objects with constant bounds we can generate
6357 -- the index check using the bounds of the type of the index
6359 if Present (A_Ent)
6360 and then Ekind (A_Ent) = E_Variable
6361 and then Is_Constant_Bound (Low_Bound (A_Range))
6362 and then Is_Constant_Bound (High_Bound (A_Range))
6363 then
6364 Range_N :=
6365 Make_Attribute_Reference (Loc,
6366 Prefix =>
6367 New_Occurrence_Of (Etype (A_Idx), Loc),
6368 Attribute_Name => Name_Range);
6370 -- For arrays with non-constant bounds we cannot generate
6371 -- the index check using the bounds of the type of the index
6372 -- since it may reference discriminants of some enclosing
6373 -- type. We obtain the bounds directly from the prefix
6374 -- object.
6376 else
6377 if Ind = 1 then
6378 Num := No_List;
6379 else
6380 Num := New_List (Make_Integer_Literal (Loc, Ind));
6381 end if;
6383 Range_N :=
6384 Make_Attribute_Reference (Loc,
6385 Prefix =>
6386 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
6387 Attribute_Name => Name_Range,
6388 Expressions => Num);
6389 end if;
6391 Insert_Action (N,
6392 Make_Raise_Constraint_Error (Loc,
6393 Condition =>
6394 Make_Not_In (Loc,
6395 Left_Opnd =>
6396 Convert_To (Base_Type (Etype (Sub)),
6397 Duplicate_Subexpr_Move_Checks (Sub)),
6398 Right_Opnd => Range_N),
6399 Reason => CE_Index_Check_Failed));
6400 end if;
6402 A_Idx := Next_Index (A_Idx);
6403 Ind := Ind + 1;
6404 Next (Sub);
6405 end loop;
6406 end;
6407 end if;
6408 end Generate_Index_Checks;
6410 --------------------------
6411 -- Generate_Range_Check --
6412 --------------------------
6414 procedure Generate_Range_Check
6415 (N : Node_Id;
6416 Target_Type : Entity_Id;
6417 Reason : RT_Exception_Code)
6419 Loc : constant Source_Ptr := Sloc (N);
6420 Source_Type : constant Entity_Id := Etype (N);
6421 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
6422 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
6424 procedure Convert_And_Check_Range;
6425 -- Convert the conversion operand to the target base type and save in
6426 -- a temporary. Then check the converted value against the range of the
6427 -- target subtype.
6429 -----------------------------
6430 -- Convert_And_Check_Range --
6431 -----------------------------
6433 procedure Convert_And_Check_Range is
6434 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
6436 begin
6437 -- We make a temporary to hold the value of the converted value
6438 -- (converted to the base type), and then do the test against this
6439 -- temporary. The conversion itself is replaced by an occurrence of
6440 -- Tnn and followed by the explicit range check. Note that checks
6441 -- are suppressed for this code, since we don't want a recursive
6442 -- range check popping up.
6444 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
6445 -- [constraint_error when Tnn not in Target_Type]
6447 Insert_Actions (N, New_List (
6448 Make_Object_Declaration (Loc,
6449 Defining_Identifier => Tnn,
6450 Object_Definition => New_Occurrence_Of (Target_Base_Type, Loc),
6451 Constant_Present => True,
6452 Expression =>
6453 Make_Type_Conversion (Loc,
6454 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
6455 Expression => Duplicate_Subexpr (N))),
6457 Make_Raise_Constraint_Error (Loc,
6458 Condition =>
6459 Make_Not_In (Loc,
6460 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
6461 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6462 Reason => Reason)),
6463 Suppress => All_Checks);
6465 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
6467 -- Set the type of N, because the declaration for Tnn might not
6468 -- be analyzed yet, as is the case if N appears within a record
6469 -- declaration, as a discriminant constraint or expression.
6471 Set_Etype (N, Target_Base_Type);
6472 end Convert_And_Check_Range;
6474 -- Start of processing for Generate_Range_Check
6476 begin
6477 -- First special case, if the source type is already within the range
6478 -- of the target type, then no check is needed (probably we should have
6479 -- stopped Do_Range_Check from being set in the first place, but better
6480 -- late than never in preventing junk code and junk flag settings.
6482 if In_Subrange_Of (Source_Type, Target_Type)
6484 -- We do NOT apply this if the source node is a literal, since in this
6485 -- case the literal has already been labeled as having the subtype of
6486 -- the target.
6488 and then not
6489 (Nkind_In (N, N_Integer_Literal, N_Real_Literal, N_Character_Literal)
6490 or else
6491 (Is_Entity_Name (N)
6492 and then Ekind (Entity (N)) = E_Enumeration_Literal))
6493 then
6494 Set_Do_Range_Check (N, False);
6495 return;
6496 end if;
6498 -- Here a check is needed. If the expander is not active, or if we are
6499 -- in GNATProve mode, then simply set the Do_Range_Check flag and we
6500 -- are done. In both these cases, we just want to see the range check
6501 -- flag set, we do not want to generate the explicit range check code.
6503 if GNATprove_Mode or else not Expander_Active then
6504 Set_Do_Range_Check (N, True);
6505 return;
6506 end if;
6508 -- Here we will generate an explicit range check, so we don't want to
6509 -- set the Do_Range check flag, since the range check is taken care of
6510 -- by the code we will generate.
6512 Set_Do_Range_Check (N, False);
6514 -- Force evaluation of the node, so that it does not get evaluated twice
6515 -- (once for the check, once for the actual reference). Such a double
6516 -- evaluation is always a potential source of inefficiency, and is
6517 -- functionally incorrect in the volatile case.
6519 if not Is_Entity_Name (N) or else Treat_As_Volatile (Entity (N)) then
6520 Force_Evaluation (N);
6521 end if;
6523 -- The easiest case is when Source_Base_Type and Target_Base_Type are
6524 -- the same since in this case we can simply do a direct check of the
6525 -- value of N against the bounds of Target_Type.
6527 -- [constraint_error when N not in Target_Type]
6529 -- Note: this is by far the most common case, for example all cases of
6530 -- checks on the RHS of assignments are in this category, but not all
6531 -- cases are like this. Notably conversions can involve two types.
6533 if Source_Base_Type = Target_Base_Type then
6535 -- Insert the explicit range check. Note that we suppress checks for
6536 -- this code, since we don't want a recursive range check popping up.
6538 Insert_Action (N,
6539 Make_Raise_Constraint_Error (Loc,
6540 Condition =>
6541 Make_Not_In (Loc,
6542 Left_Opnd => Duplicate_Subexpr (N),
6543 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6544 Reason => Reason),
6545 Suppress => All_Checks);
6547 -- Next test for the case where the target type is within the bounds
6548 -- of the base type of the source type, since in this case we can
6549 -- simply convert these bounds to the base type of T to do the test.
6551 -- [constraint_error when N not in
6552 -- Source_Base_Type (Target_Type'First)
6553 -- ..
6554 -- Source_Base_Type(Target_Type'Last))]
6556 -- The conversions will always work and need no check
6558 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
6559 -- of converting from an enumeration value to an integer type, such as
6560 -- occurs for the case of generating a range check on Enum'Val(Exp)
6561 -- (which used to be handled by gigi). This is OK, since the conversion
6562 -- itself does not require a check.
6564 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
6566 -- Insert the explicit range check. Note that we suppress checks for
6567 -- this code, since we don't want a recursive range check popping up.
6569 if Is_Discrete_Type (Source_Base_Type)
6570 and then
6571 Is_Discrete_Type (Target_Base_Type)
6572 then
6573 Insert_Action (N,
6574 Make_Raise_Constraint_Error (Loc,
6575 Condition =>
6576 Make_Not_In (Loc,
6577 Left_Opnd => Duplicate_Subexpr (N),
6579 Right_Opnd =>
6580 Make_Range (Loc,
6581 Low_Bound =>
6582 Unchecked_Convert_To (Source_Base_Type,
6583 Make_Attribute_Reference (Loc,
6584 Prefix =>
6585 New_Occurrence_Of (Target_Type, Loc),
6586 Attribute_Name => Name_First)),
6588 High_Bound =>
6589 Unchecked_Convert_To (Source_Base_Type,
6590 Make_Attribute_Reference (Loc,
6591 Prefix =>
6592 New_Occurrence_Of (Target_Type, Loc),
6593 Attribute_Name => Name_Last)))),
6594 Reason => Reason),
6595 Suppress => All_Checks);
6597 -- For conversions involving at least one type that is not discrete,
6598 -- first convert to target type and then generate the range check.
6599 -- This avoids problems with values that are close to a bound of the
6600 -- target type that would fail a range check when done in a larger
6601 -- source type before converting but would pass if converted with
6602 -- rounding and then checked (such as in float-to-float conversions).
6604 else
6605 Convert_And_Check_Range;
6606 end if;
6608 -- Note that at this stage we now that the Target_Base_Type is not in
6609 -- the range of the Source_Base_Type (since even the Target_Type itself
6610 -- is not in this range). It could still be the case that Source_Type is
6611 -- in range of the target base type since we have not checked that case.
6613 -- If that is the case, we can freely convert the source to the target,
6614 -- and then test the target result against the bounds.
6616 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
6617 Convert_And_Check_Range;
6619 -- At this stage, we know that we have two scalar types, which are
6620 -- directly convertible, and where neither scalar type has a base
6621 -- range that is in the range of the other scalar type.
6623 -- The only way this can happen is with a signed and unsigned type.
6624 -- So test for these two cases:
6626 else
6627 -- Case of the source is unsigned and the target is signed
6629 if Is_Unsigned_Type (Source_Base_Type)
6630 and then not Is_Unsigned_Type (Target_Base_Type)
6631 then
6632 -- If the source is unsigned and the target is signed, then we
6633 -- know that the source is not shorter than the target (otherwise
6634 -- the source base type would be in the target base type range).
6636 -- In other words, the unsigned type is either the same size as
6637 -- the target, or it is larger. It cannot be smaller.
6639 pragma Assert
6640 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
6642 -- We only need to check the low bound if the low bound of the
6643 -- target type is non-negative. If the low bound of the target
6644 -- type is negative, then we know that we will fit fine.
6646 -- If the high bound of the target type is negative, then we
6647 -- know we have a constraint error, since we can't possibly
6648 -- have a negative source.
6650 -- With these two checks out of the way, we can do the check
6651 -- using the source type safely
6653 -- This is definitely the most annoying case.
6655 -- [constraint_error
6656 -- when (Target_Type'First >= 0
6657 -- and then
6658 -- N < Source_Base_Type (Target_Type'First))
6659 -- or else Target_Type'Last < 0
6660 -- or else N > Source_Base_Type (Target_Type'Last)];
6662 -- We turn off all checks since we know that the conversions
6663 -- will work fine, given the guards for negative values.
6665 Insert_Action (N,
6666 Make_Raise_Constraint_Error (Loc,
6667 Condition =>
6668 Make_Or_Else (Loc,
6669 Make_Or_Else (Loc,
6670 Left_Opnd =>
6671 Make_And_Then (Loc,
6672 Left_Opnd => Make_Op_Ge (Loc,
6673 Left_Opnd =>
6674 Make_Attribute_Reference (Loc,
6675 Prefix =>
6676 New_Occurrence_Of (Target_Type, Loc),
6677 Attribute_Name => Name_First),
6678 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
6680 Right_Opnd =>
6681 Make_Op_Lt (Loc,
6682 Left_Opnd => Duplicate_Subexpr (N),
6683 Right_Opnd =>
6684 Convert_To (Source_Base_Type,
6685 Make_Attribute_Reference (Loc,
6686 Prefix =>
6687 New_Occurrence_Of (Target_Type, Loc),
6688 Attribute_Name => Name_First)))),
6690 Right_Opnd =>
6691 Make_Op_Lt (Loc,
6692 Left_Opnd =>
6693 Make_Attribute_Reference (Loc,
6694 Prefix => New_Occurrence_Of (Target_Type, Loc),
6695 Attribute_Name => Name_Last),
6696 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
6698 Right_Opnd =>
6699 Make_Op_Gt (Loc,
6700 Left_Opnd => Duplicate_Subexpr (N),
6701 Right_Opnd =>
6702 Convert_To (Source_Base_Type,
6703 Make_Attribute_Reference (Loc,
6704 Prefix => New_Occurrence_Of (Target_Type, Loc),
6705 Attribute_Name => Name_Last)))),
6707 Reason => Reason),
6708 Suppress => All_Checks);
6710 -- Only remaining possibility is that the source is signed and
6711 -- the target is unsigned.
6713 else
6714 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
6715 and then Is_Unsigned_Type (Target_Base_Type));
6717 -- If the source is signed and the target is unsigned, then we
6718 -- know that the target is not shorter than the source (otherwise
6719 -- the target base type would be in the source base type range).
6721 -- In other words, the unsigned type is either the same size as
6722 -- the target, or it is larger. It cannot be smaller.
6724 -- Clearly we have an error if the source value is negative since
6725 -- no unsigned type can have negative values. If the source type
6726 -- is non-negative, then the check can be done using the target
6727 -- type.
6729 -- Tnn : constant Target_Base_Type (N) := Target_Type;
6731 -- [constraint_error
6732 -- when N < 0 or else Tnn not in Target_Type];
6734 -- We turn off all checks for the conversion of N to the target
6735 -- base type, since we generate the explicit check to ensure that
6736 -- the value is non-negative
6738 declare
6739 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
6741 begin
6742 Insert_Actions (N, New_List (
6743 Make_Object_Declaration (Loc,
6744 Defining_Identifier => Tnn,
6745 Object_Definition =>
6746 New_Occurrence_Of (Target_Base_Type, Loc),
6747 Constant_Present => True,
6748 Expression =>
6749 Make_Unchecked_Type_Conversion (Loc,
6750 Subtype_Mark =>
6751 New_Occurrence_Of (Target_Base_Type, Loc),
6752 Expression => Duplicate_Subexpr (N))),
6754 Make_Raise_Constraint_Error (Loc,
6755 Condition =>
6756 Make_Or_Else (Loc,
6757 Left_Opnd =>
6758 Make_Op_Lt (Loc,
6759 Left_Opnd => Duplicate_Subexpr (N),
6760 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
6762 Right_Opnd =>
6763 Make_Not_In (Loc,
6764 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
6765 Right_Opnd =>
6766 New_Occurrence_Of (Target_Type, Loc))),
6768 Reason => Reason)),
6769 Suppress => All_Checks);
6771 -- Set the Etype explicitly, because Insert_Actions may have
6772 -- placed the declaration in the freeze list for an enclosing
6773 -- construct, and thus it is not analyzed yet.
6775 Set_Etype (Tnn, Target_Base_Type);
6776 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
6777 end;
6778 end if;
6779 end if;
6780 end Generate_Range_Check;
6782 ------------------
6783 -- Get_Check_Id --
6784 ------------------
6786 function Get_Check_Id (N : Name_Id) return Check_Id is
6787 begin
6788 -- For standard check name, we can do a direct computation
6790 if N in First_Check_Name .. Last_Check_Name then
6791 return Check_Id (N - (First_Check_Name - 1));
6793 -- For non-standard names added by pragma Check_Name, search table
6795 else
6796 for J in All_Checks + 1 .. Check_Names.Last loop
6797 if Check_Names.Table (J) = N then
6798 return J;
6799 end if;
6800 end loop;
6801 end if;
6803 -- No matching name found
6805 return No_Check_Id;
6806 end Get_Check_Id;
6808 ---------------------
6809 -- Get_Discriminal --
6810 ---------------------
6812 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
6813 Loc : constant Source_Ptr := Sloc (E);
6814 D : Entity_Id;
6815 Sc : Entity_Id;
6817 begin
6818 -- The bound can be a bona fide parameter of a protected operation,
6819 -- rather than a prival encoded as an in-parameter.
6821 if No (Discriminal_Link (Entity (Bound))) then
6822 return Bound;
6823 end if;
6825 -- Climb the scope stack looking for an enclosing protected type. If
6826 -- we run out of scopes, return the bound itself.
6828 Sc := Scope (E);
6829 while Present (Sc) loop
6830 if Sc = Standard_Standard then
6831 return Bound;
6832 elsif Ekind (Sc) = E_Protected_Type then
6833 exit;
6834 end if;
6836 Sc := Scope (Sc);
6837 end loop;
6839 D := First_Discriminant (Sc);
6840 while Present (D) loop
6841 if Chars (D) = Chars (Bound) then
6842 return New_Occurrence_Of (Discriminal (D), Loc);
6843 end if;
6845 Next_Discriminant (D);
6846 end loop;
6848 return Bound;
6849 end Get_Discriminal;
6851 ----------------------
6852 -- Get_Range_Checks --
6853 ----------------------
6855 function Get_Range_Checks
6856 (Ck_Node : Node_Id;
6857 Target_Typ : Entity_Id;
6858 Source_Typ : Entity_Id := Empty;
6859 Warn_Node : Node_Id := Empty) return Check_Result
6861 begin
6862 return
6863 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
6864 end Get_Range_Checks;
6866 ------------------
6867 -- Guard_Access --
6868 ------------------
6870 function Guard_Access
6871 (Cond : Node_Id;
6872 Loc : Source_Ptr;
6873 Ck_Node : Node_Id) return Node_Id
6875 begin
6876 if Nkind (Cond) = N_Or_Else then
6877 Set_Paren_Count (Cond, 1);
6878 end if;
6880 if Nkind (Ck_Node) = N_Allocator then
6881 return Cond;
6883 else
6884 return
6885 Make_And_Then (Loc,
6886 Left_Opnd =>
6887 Make_Op_Ne (Loc,
6888 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
6889 Right_Opnd => Make_Null (Loc)),
6890 Right_Opnd => Cond);
6891 end if;
6892 end Guard_Access;
6894 -----------------------------
6895 -- Index_Checks_Suppressed --
6896 -----------------------------
6898 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
6899 begin
6900 if Present (E) and then Checks_May_Be_Suppressed (E) then
6901 return Is_Check_Suppressed (E, Index_Check);
6902 else
6903 return Scope_Suppress.Suppress (Index_Check);
6904 end if;
6905 end Index_Checks_Suppressed;
6907 ----------------
6908 -- Initialize --
6909 ----------------
6911 procedure Initialize is
6912 begin
6913 for J in Determine_Range_Cache_N'Range loop
6914 Determine_Range_Cache_N (J) := Empty;
6915 end loop;
6917 Check_Names.Init;
6919 for J in Int range 1 .. All_Checks loop
6920 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
6921 end loop;
6922 end Initialize;
6924 -------------------------
6925 -- Insert_Range_Checks --
6926 -------------------------
6928 procedure Insert_Range_Checks
6929 (Checks : Check_Result;
6930 Node : Node_Id;
6931 Suppress_Typ : Entity_Id;
6932 Static_Sloc : Source_Ptr := No_Location;
6933 Flag_Node : Node_Id := Empty;
6934 Do_Before : Boolean := False)
6936 Internal_Flag_Node : Node_Id := Flag_Node;
6937 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
6939 Check_Node : Node_Id;
6940 Checks_On : constant Boolean :=
6941 (not Index_Checks_Suppressed (Suppress_Typ))
6942 or else (not Range_Checks_Suppressed (Suppress_Typ));
6944 begin
6945 -- For now we just return if Checks_On is false, however this should be
6946 -- enhanced to check for an always True value in the condition and to
6947 -- generate a compilation warning???
6949 if not Expander_Active or not Checks_On then
6950 return;
6951 end if;
6953 if Static_Sloc = No_Location then
6954 Internal_Static_Sloc := Sloc (Node);
6955 end if;
6957 if No (Flag_Node) then
6958 Internal_Flag_Node := Node;
6959 end if;
6961 for J in 1 .. 2 loop
6962 exit when No (Checks (J));
6964 if Nkind (Checks (J)) = N_Raise_Constraint_Error
6965 and then Present (Condition (Checks (J)))
6966 then
6967 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
6968 Check_Node := Checks (J);
6969 Mark_Rewrite_Insertion (Check_Node);
6971 if Do_Before then
6972 Insert_Before_And_Analyze (Node, Check_Node);
6973 else
6974 Insert_After_And_Analyze (Node, Check_Node);
6975 end if;
6977 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
6978 end if;
6980 else
6981 Check_Node :=
6982 Make_Raise_Constraint_Error (Internal_Static_Sloc,
6983 Reason => CE_Range_Check_Failed);
6984 Mark_Rewrite_Insertion (Check_Node);
6986 if Do_Before then
6987 Insert_Before_And_Analyze (Node, Check_Node);
6988 else
6989 Insert_After_And_Analyze (Node, Check_Node);
6990 end if;
6991 end if;
6992 end loop;
6993 end Insert_Range_Checks;
6995 ------------------------
6996 -- Insert_Valid_Check --
6997 ------------------------
6999 procedure Insert_Valid_Check (Expr : Node_Id) is
7000 Loc : constant Source_Ptr := Sloc (Expr);
7001 Typ : constant Entity_Id := Etype (Expr);
7002 Exp : Node_Id;
7004 begin
7005 -- Do not insert if checks off, or if not checking validity or
7006 -- if expression is known to be valid
7008 if not Validity_Checks_On
7009 or else Range_Or_Validity_Checks_Suppressed (Expr)
7010 or else Expr_Known_Valid (Expr)
7011 then
7012 return;
7013 end if;
7015 -- Do not insert checks within a predicate function. This will arise
7016 -- if the current unit and the predicate function are being compiled
7017 -- with validity checks enabled.
7019 if Present (Predicate_Function (Typ))
7020 and then Current_Scope = Predicate_Function (Typ)
7021 then
7022 return;
7023 end if;
7025 -- If the expression is a packed component of a modular type of the
7026 -- right size, the data is always valid.
7028 if Nkind (Expr) = N_Selected_Component
7029 and then Present (Component_Clause (Entity (Selector_Name (Expr))))
7030 and then Is_Modular_Integer_Type (Typ)
7031 and then Modulus (Typ) = 2 ** Esize (Entity (Selector_Name (Expr)))
7032 then
7033 return;
7034 end if;
7036 -- If we have a checked conversion, then validity check applies to
7037 -- the expression inside the conversion, not the result, since if
7038 -- the expression inside is valid, then so is the conversion result.
7040 Exp := Expr;
7041 while Nkind (Exp) = N_Type_Conversion loop
7042 Exp := Expression (Exp);
7043 end loop;
7045 -- We are about to insert the validity check for Exp. We save and
7046 -- reset the Do_Range_Check flag over this validity check, and then
7047 -- put it back for the final original reference (Exp may be rewritten).
7049 declare
7050 DRC : constant Boolean := Do_Range_Check (Exp);
7051 PV : Node_Id;
7052 CE : Node_Id;
7054 begin
7055 Set_Do_Range_Check (Exp, False);
7057 -- Force evaluation to avoid multiple reads for atomic/volatile
7059 -- Note: we set Name_Req to False. We used to set it to True, with
7060 -- the thinking that a name is required as the prefix of the 'Valid
7061 -- call, but in fact the check that the prefix of an attribute is
7062 -- a name is in the parser, and we just don't require it here.
7063 -- Moreover, when we set Name_Req to True, that interfered with the
7064 -- checking for Volatile, since we couldn't just capture the value.
7066 if Is_Entity_Name (Exp)
7067 and then Is_Volatile (Entity (Exp))
7068 then
7069 -- Same reasoning as above for setting Name_Req to False
7071 Force_Evaluation (Exp, Name_Req => False);
7072 end if;
7074 -- Build the prefix for the 'Valid call
7076 PV := Duplicate_Subexpr_No_Checks (Exp, Name_Req => False);
7078 -- A rather specialized test. If PV is an analyzed expression which
7079 -- is an indexed component of a packed array that has not been
7080 -- properly expanded, turn off its Analyzed flag to make sure it
7081 -- gets properly reexpanded. If the prefix is an access value,
7082 -- the dereference will be added later.
7084 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
7085 -- an analyze with the old parent pointer. This may point e.g. to
7086 -- a subprogram call, which deactivates this expansion.
7088 if Analyzed (PV)
7089 and then Nkind (PV) = N_Indexed_Component
7090 and then Is_Array_Type (Etype (Prefix (PV)))
7091 and then Present (Packed_Array_Impl_Type (Etype (Prefix (PV))))
7092 then
7093 Set_Analyzed (PV, False);
7094 end if;
7096 -- Build the raise CE node to check for validity. We build a type
7097 -- qualification for the prefix, since it may not be of the form of
7098 -- a name, and we don't care in this context!
7100 CE :=
7101 Make_Raise_Constraint_Error (Loc,
7102 Condition =>
7103 Make_Op_Not (Loc,
7104 Right_Opnd =>
7105 Make_Attribute_Reference (Loc,
7106 Prefix => PV,
7107 Attribute_Name => Name_Valid)),
7108 Reason => CE_Invalid_Data);
7110 -- Insert the validity check. Note that we do this with validity
7111 -- checks turned off, to avoid recursion, we do not want validity
7112 -- checks on the validity checking code itself.
7114 Insert_Action (Expr, CE, Suppress => Validity_Check);
7116 -- If the expression is a reference to an element of a bit-packed
7117 -- array, then it is rewritten as a renaming declaration. If the
7118 -- expression is an actual in a call, it has not been expanded,
7119 -- waiting for the proper point at which to do it. The same happens
7120 -- with renamings, so that we have to force the expansion now. This
7121 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
7122 -- and exp_ch6.adb.
7124 if Is_Entity_Name (Exp)
7125 and then Nkind (Parent (Entity (Exp))) =
7126 N_Object_Renaming_Declaration
7127 then
7128 declare
7129 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
7130 begin
7131 if Nkind (Old_Exp) = N_Indexed_Component
7132 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
7133 then
7134 Expand_Packed_Element_Reference (Old_Exp);
7135 end if;
7136 end;
7137 end if;
7139 -- Put back the Do_Range_Check flag on the resulting (possibly
7140 -- rewritten) expression.
7142 -- Note: it might be thought that a validity check is not required
7143 -- when a range check is present, but that's not the case, because
7144 -- the back end is allowed to assume for the range check that the
7145 -- operand is within its declared range (an assumption that validity
7146 -- checking is all about NOT assuming).
7148 -- Note: no need to worry about Possible_Local_Raise here, it will
7149 -- already have been called if original node has Do_Range_Check set.
7151 Set_Do_Range_Check (Exp, DRC);
7152 end;
7153 end Insert_Valid_Check;
7155 -------------------------------------
7156 -- Is_Signed_Integer_Arithmetic_Op --
7157 -------------------------------------
7159 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean is
7160 begin
7161 case Nkind (N) is
7162 when N_Op_Abs | N_Op_Add | N_Op_Divide | N_Op_Expon |
7163 N_Op_Minus | N_Op_Mod | N_Op_Multiply | N_Op_Plus |
7164 N_Op_Rem | N_Op_Subtract =>
7165 return Is_Signed_Integer_Type (Etype (N));
7167 when N_If_Expression | N_Case_Expression =>
7168 return Is_Signed_Integer_Type (Etype (N));
7170 when others =>
7171 return False;
7172 end case;
7173 end Is_Signed_Integer_Arithmetic_Op;
7175 ----------------------------------
7176 -- Install_Null_Excluding_Check --
7177 ----------------------------------
7179 procedure Install_Null_Excluding_Check (N : Node_Id) is
7180 Loc : constant Source_Ptr := Sloc (Parent (N));
7181 Typ : constant Entity_Id := Etype (N);
7183 function Safe_To_Capture_In_Parameter_Value return Boolean;
7184 -- Determines if it is safe to capture Known_Non_Null status for an
7185 -- the entity referenced by node N. The caller ensures that N is indeed
7186 -- an entity name. It is safe to capture the non-null status for an IN
7187 -- parameter when the reference occurs within a declaration that is sure
7188 -- to be executed as part of the declarative region.
7190 procedure Mark_Non_Null;
7191 -- After installation of check, if the node in question is an entity
7192 -- name, then mark this entity as non-null if possible.
7194 function Safe_To_Capture_In_Parameter_Value return Boolean is
7195 E : constant Entity_Id := Entity (N);
7196 S : constant Entity_Id := Current_Scope;
7197 S_Par : Node_Id;
7199 begin
7200 if Ekind (E) /= E_In_Parameter then
7201 return False;
7202 end if;
7204 -- Two initial context checks. We must be inside a subprogram body
7205 -- with declarations and reference must not appear in nested scopes.
7207 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
7208 or else Scope (E) /= S
7209 then
7210 return False;
7211 end if;
7213 S_Par := Parent (Parent (S));
7215 if Nkind (S_Par) /= N_Subprogram_Body
7216 or else No (Declarations (S_Par))
7217 then
7218 return False;
7219 end if;
7221 declare
7222 N_Decl : Node_Id;
7223 P : Node_Id;
7225 begin
7226 -- Retrieve the declaration node of N (if any). Note that N
7227 -- may be a part of a complex initialization expression.
7229 P := Parent (N);
7230 N_Decl := Empty;
7231 while Present (P) loop
7233 -- If we have a short circuit form, and we are within the right
7234 -- hand expression, we return false, since the right hand side
7235 -- is not guaranteed to be elaborated.
7237 if Nkind (P) in N_Short_Circuit
7238 and then N = Right_Opnd (P)
7239 then
7240 return False;
7241 end if;
7243 -- Similarly, if we are in an if expression and not part of the
7244 -- condition, then we return False, since neither the THEN or
7245 -- ELSE dependent expressions will always be elaborated.
7247 if Nkind (P) = N_If_Expression
7248 and then N /= First (Expressions (P))
7249 then
7250 return False;
7251 end if;
7253 -- If within a case expression, and not part of the expression,
7254 -- then return False, since a particular dependent expression
7255 -- may not always be elaborated
7257 if Nkind (P) = N_Case_Expression
7258 and then N /= Expression (P)
7259 then
7260 return False;
7261 end if;
7263 -- While traversing the parent chain, if node N belongs to a
7264 -- statement, then it may never appear in a declarative region.
7266 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
7267 or else Nkind (P) = N_Procedure_Call_Statement
7268 then
7269 return False;
7270 end if;
7272 -- If we are at a declaration, record it and exit
7274 if Nkind (P) in N_Declaration
7275 and then Nkind (P) not in N_Subprogram_Specification
7276 then
7277 N_Decl := P;
7278 exit;
7279 end if;
7281 P := Parent (P);
7282 end loop;
7284 if No (N_Decl) then
7285 return False;
7286 end if;
7288 return List_Containing (N_Decl) = Declarations (S_Par);
7289 end;
7290 end Safe_To_Capture_In_Parameter_Value;
7292 -------------------
7293 -- Mark_Non_Null --
7294 -------------------
7296 procedure Mark_Non_Null is
7297 begin
7298 -- Only case of interest is if node N is an entity name
7300 if Is_Entity_Name (N) then
7302 -- For sure, we want to clear an indication that this is known to
7303 -- be null, since if we get past this check, it definitely is not.
7305 Set_Is_Known_Null (Entity (N), False);
7307 -- We can mark the entity as known to be non-null if either it is
7308 -- safe to capture the value, or in the case of an IN parameter,
7309 -- which is a constant, if the check we just installed is in the
7310 -- declarative region of the subprogram body. In this latter case,
7311 -- a check is decisive for the rest of the body if the expression
7312 -- is sure to be elaborated, since we know we have to elaborate
7313 -- all declarations before executing the body.
7315 -- Couldn't this always be part of Safe_To_Capture_Value ???
7317 if Safe_To_Capture_Value (N, Entity (N))
7318 or else Safe_To_Capture_In_Parameter_Value
7319 then
7320 Set_Is_Known_Non_Null (Entity (N));
7321 end if;
7322 end if;
7323 end Mark_Non_Null;
7325 -- Start of processing for Install_Null_Excluding_Check
7327 begin
7328 pragma Assert (Is_Access_Type (Typ));
7330 -- No check inside a generic, check will be emitted in instance
7332 if Inside_A_Generic then
7333 return;
7334 end if;
7336 -- No check needed if known to be non-null
7338 if Known_Non_Null (N) then
7339 return;
7340 end if;
7342 -- If known to be null, here is where we generate a compile time check
7344 if Known_Null (N) then
7346 -- Avoid generating warning message inside init procs. In SPARK mode
7347 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
7348 -- since it will be turned into an error in any case.
7350 if (not Inside_Init_Proc or else SPARK_Mode = On)
7352 -- Do not emit the warning within a conditional expression,
7353 -- where the expression might not be evaluated, and the warning
7354 -- appear as extraneous noise.
7356 and then not Within_Case_Or_If_Expression (N)
7357 then
7358 Apply_Compile_Time_Constraint_Error
7359 (N, "null value not allowed here??", CE_Access_Check_Failed);
7361 -- Remaining cases, where we silently insert the raise
7363 else
7364 Insert_Action (N,
7365 Make_Raise_Constraint_Error (Loc,
7366 Reason => CE_Access_Check_Failed));
7367 end if;
7369 Mark_Non_Null;
7370 return;
7371 end if;
7373 -- If entity is never assigned, for sure a warning is appropriate
7375 if Is_Entity_Name (N) then
7376 Check_Unset_Reference (N);
7377 end if;
7379 -- No check needed if checks are suppressed on the range. Note that we
7380 -- don't set Is_Known_Non_Null in this case (we could legitimately do
7381 -- so, since the program is erroneous, but we don't like to casually
7382 -- propagate such conclusions from erroneosity).
7384 if Access_Checks_Suppressed (Typ) then
7385 return;
7386 end if;
7388 -- No check needed for access to concurrent record types generated by
7389 -- the expander. This is not just an optimization (though it does indeed
7390 -- remove junk checks). It also avoids generation of junk warnings.
7392 if Nkind (N) in N_Has_Chars
7393 and then Chars (N) = Name_uObject
7394 and then Is_Concurrent_Record_Type
7395 (Directly_Designated_Type (Etype (N)))
7396 then
7397 return;
7398 end if;
7400 -- No check needed in interface thunks since the runtime check is
7401 -- already performed at the caller side.
7403 if Is_Thunk (Current_Scope) then
7404 return;
7405 end if;
7407 -- No check needed for the Get_Current_Excep.all.all idiom generated by
7408 -- the expander within exception handlers, since we know that the value
7409 -- can never be null.
7411 -- Is this really the right way to do this? Normally we generate such
7412 -- code in the expander with checks off, and that's how we suppress this
7413 -- kind of junk check ???
7415 if Nkind (N) = N_Function_Call
7416 and then Nkind (Name (N)) = N_Explicit_Dereference
7417 and then Nkind (Prefix (Name (N))) = N_Identifier
7418 and then Is_RTE (Entity (Prefix (Name (N))), RE_Get_Current_Excep)
7419 then
7420 return;
7421 end if;
7423 -- Otherwise install access check
7425 Insert_Action (N,
7426 Make_Raise_Constraint_Error (Loc,
7427 Condition =>
7428 Make_Op_Eq (Loc,
7429 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
7430 Right_Opnd => Make_Null (Loc)),
7431 Reason => CE_Access_Check_Failed));
7433 Mark_Non_Null;
7434 end Install_Null_Excluding_Check;
7436 --------------------------
7437 -- Install_Static_Check --
7438 --------------------------
7440 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
7441 Stat : constant Boolean := Is_OK_Static_Expression (R_Cno);
7442 Typ : constant Entity_Id := Etype (R_Cno);
7444 begin
7445 Rewrite (R_Cno,
7446 Make_Raise_Constraint_Error (Loc,
7447 Reason => CE_Range_Check_Failed));
7448 Set_Analyzed (R_Cno);
7449 Set_Etype (R_Cno, Typ);
7450 Set_Raises_Constraint_Error (R_Cno);
7451 Set_Is_Static_Expression (R_Cno, Stat);
7453 -- Now deal with possible local raise handling
7455 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
7456 end Install_Static_Check;
7458 -------------------------
7459 -- Is_Check_Suppressed --
7460 -------------------------
7462 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean is
7463 Ptr : Suppress_Stack_Entry_Ptr;
7465 begin
7466 -- First search the local entity suppress stack. We search this from the
7467 -- top of the stack down so that we get the innermost entry that applies
7468 -- to this case if there are nested entries.
7470 Ptr := Local_Suppress_Stack_Top;
7471 while Ptr /= null loop
7472 if (Ptr.Entity = Empty or else Ptr.Entity = E)
7473 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
7474 then
7475 return Ptr.Suppress;
7476 end if;
7478 Ptr := Ptr.Prev;
7479 end loop;
7481 -- Now search the global entity suppress table for a matching entry.
7482 -- We also search this from the top down so that if there are multiple
7483 -- pragmas for the same entity, the last one applies (not clear what
7484 -- or whether the RM specifies this handling, but it seems reasonable).
7486 Ptr := Global_Suppress_Stack_Top;
7487 while Ptr /= null loop
7488 if (Ptr.Entity = Empty or else Ptr.Entity = E)
7489 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
7490 then
7491 return Ptr.Suppress;
7492 end if;
7494 Ptr := Ptr.Prev;
7495 end loop;
7497 -- If we did not find a matching entry, then use the normal scope
7498 -- suppress value after all (actually this will be the global setting
7499 -- since it clearly was not overridden at any point). For a predefined
7500 -- check, we test the specific flag. For a user defined check, we check
7501 -- the All_Checks flag. The Overflow flag requires special handling to
7502 -- deal with the General vs Assertion case
7504 if C = Overflow_Check then
7505 return Overflow_Checks_Suppressed (Empty);
7506 elsif C in Predefined_Check_Id then
7507 return Scope_Suppress.Suppress (C);
7508 else
7509 return Scope_Suppress.Suppress (All_Checks);
7510 end if;
7511 end Is_Check_Suppressed;
7513 ---------------------
7514 -- Kill_All_Checks --
7515 ---------------------
7517 procedure Kill_All_Checks is
7518 begin
7519 if Debug_Flag_CC then
7520 w ("Kill_All_Checks");
7521 end if;
7523 -- We reset the number of saved checks to zero, and also modify all
7524 -- stack entries for statement ranges to indicate that the number of
7525 -- checks at each level is now zero.
7527 Num_Saved_Checks := 0;
7529 -- Note: the Int'Min here avoids any possibility of J being out of
7530 -- range when called from e.g. Conditional_Statements_Begin.
7532 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
7533 Saved_Checks_Stack (J) := 0;
7534 end loop;
7535 end Kill_All_Checks;
7537 -----------------
7538 -- Kill_Checks --
7539 -----------------
7541 procedure Kill_Checks (V : Entity_Id) is
7542 begin
7543 if Debug_Flag_CC then
7544 w ("Kill_Checks for entity", Int (V));
7545 end if;
7547 for J in 1 .. Num_Saved_Checks loop
7548 if Saved_Checks (J).Entity = V then
7549 if Debug_Flag_CC then
7550 w (" Checks killed for saved check ", J);
7551 end if;
7553 Saved_Checks (J).Killed := True;
7554 end if;
7555 end loop;
7556 end Kill_Checks;
7558 ------------------------------
7559 -- Length_Checks_Suppressed --
7560 ------------------------------
7562 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
7563 begin
7564 if Present (E) and then Checks_May_Be_Suppressed (E) then
7565 return Is_Check_Suppressed (E, Length_Check);
7566 else
7567 return Scope_Suppress.Suppress (Length_Check);
7568 end if;
7569 end Length_Checks_Suppressed;
7571 -----------------------
7572 -- Make_Bignum_Block --
7573 -----------------------
7575 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id is
7576 M : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uM);
7577 begin
7578 return
7579 Make_Block_Statement (Loc,
7580 Declarations =>
7581 New_List (Build_SS_Mark_Call (Loc, M)),
7582 Handled_Statement_Sequence =>
7583 Make_Handled_Sequence_Of_Statements (Loc,
7584 Statements => New_List (Build_SS_Release_Call (Loc, M))));
7585 end Make_Bignum_Block;
7587 ----------------------------------
7588 -- Minimize_Eliminate_Overflows --
7589 ----------------------------------
7591 -- This is a recursive routine that is called at the top of an expression
7592 -- tree to properly process overflow checking for a whole subtree by making
7593 -- recursive calls to process operands. This processing may involve the use
7594 -- of bignum or long long integer arithmetic, which will change the types
7595 -- of operands and results. That's why we can't do this bottom up (since
7596 -- it would interfere with semantic analysis).
7598 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
7599 -- the operator expansion routines, as well as the expansion routines for
7600 -- if/case expression, do nothing (for the moment) except call the routine
7601 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
7602 -- routine does nothing for non top-level nodes, so at the point where the
7603 -- call is made for the top level node, the entire expression subtree has
7604 -- not been expanded, or processed for overflow. All that has to happen as
7605 -- a result of the top level call to this routine.
7607 -- As noted above, the overflow processing works by making recursive calls
7608 -- for the operands, and figuring out what to do, based on the processing
7609 -- of these operands (e.g. if a bignum operand appears, the parent op has
7610 -- to be done in bignum mode), and the determined ranges of the operands.
7612 -- After possible rewriting of a constituent subexpression node, a call is
7613 -- made to either reexpand the node (if nothing has changed) or reanalyze
7614 -- the node (if it has been modified by the overflow check processing). The
7615 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
7616 -- a recursive call into the whole overflow apparatus, an important rule
7617 -- for this call is that the overflow handling mode must be temporarily set
7618 -- to STRICT.
7620 procedure Minimize_Eliminate_Overflows
7621 (N : Node_Id;
7622 Lo : out Uint;
7623 Hi : out Uint;
7624 Top_Level : Boolean)
7626 Rtyp : constant Entity_Id := Etype (N);
7627 pragma Assert (Is_Signed_Integer_Type (Rtyp));
7628 -- Result type, must be a signed integer type
7630 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
7631 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
7633 Loc : constant Source_Ptr := Sloc (N);
7635 Rlo, Rhi : Uint;
7636 -- Ranges of values for right operand (operator case)
7638 Llo, Lhi : Uint;
7639 -- Ranges of values for left operand (operator case)
7641 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
7642 -- Operands and results are of this type when we convert
7644 LLLo : constant Uint := Intval (Type_Low_Bound (LLIB));
7645 LLHi : constant Uint := Intval (Type_High_Bound (LLIB));
7646 -- Bounds of Long_Long_Integer
7648 Binary : constant Boolean := Nkind (N) in N_Binary_Op;
7649 -- Indicates binary operator case
7651 OK : Boolean;
7652 -- Used in call to Determine_Range
7654 Bignum_Operands : Boolean;
7655 -- Set True if one or more operands is already of type Bignum, meaning
7656 -- that for sure (regardless of Top_Level setting) we are committed to
7657 -- doing the operation in Bignum mode (or in the case of a case or if
7658 -- expression, converting all the dependent expressions to Bignum).
7660 Long_Long_Integer_Operands : Boolean;
7661 -- Set True if one or more operands is already of type Long_Long_Integer
7662 -- which means that if the result is known to be in the result type
7663 -- range, then we must convert such operands back to the result type.
7665 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False);
7666 -- This is called when we have modified the node and we therefore need
7667 -- to reanalyze it. It is important that we reset the mode to STRICT for
7668 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
7669 -- we would reenter this routine recursively which would not be good.
7670 -- The argument Suppress is set True if we also want to suppress
7671 -- overflow checking for the reexpansion (this is set when we know
7672 -- overflow is not possible). Typ is the type for the reanalysis.
7674 procedure Reexpand (Suppress : Boolean := False);
7675 -- This is like Reanalyze, but does not do the Analyze step, it only
7676 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
7677 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
7678 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
7679 -- Note that skipping reanalysis is not just an optimization, testing
7680 -- has showed up several complex cases in which reanalyzing an already
7681 -- analyzed node causes incorrect behavior.
7683 function In_Result_Range return Boolean;
7684 -- Returns True iff Lo .. Hi are within range of the result type
7686 procedure Max (A : in out Uint; B : Uint);
7687 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
7689 procedure Min (A : in out Uint; B : Uint);
7690 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
7692 ---------------------
7693 -- In_Result_Range --
7694 ---------------------
7696 function In_Result_Range return Boolean is
7697 begin
7698 if Lo = No_Uint or else Hi = No_Uint then
7699 return False;
7701 elsif Is_OK_Static_Subtype (Etype (N)) then
7702 return Lo >= Expr_Value (Type_Low_Bound (Rtyp))
7703 and then
7704 Hi <= Expr_Value (Type_High_Bound (Rtyp));
7706 else
7707 return Lo >= Expr_Value (Type_Low_Bound (Base_Type (Rtyp)))
7708 and then
7709 Hi <= Expr_Value (Type_High_Bound (Base_Type (Rtyp)));
7710 end if;
7711 end In_Result_Range;
7713 ---------
7714 -- Max --
7715 ---------
7717 procedure Max (A : in out Uint; B : Uint) is
7718 begin
7719 if A = No_Uint or else B > A then
7720 A := B;
7721 end if;
7722 end Max;
7724 ---------
7725 -- Min --
7726 ---------
7728 procedure Min (A : in out Uint; B : Uint) is
7729 begin
7730 if A = No_Uint or else B < A then
7731 A := B;
7732 end if;
7733 end Min;
7735 ---------------
7736 -- Reanalyze --
7737 ---------------
7739 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False) is
7740 Svg : constant Overflow_Mode_Type :=
7741 Scope_Suppress.Overflow_Mode_General;
7742 Sva : constant Overflow_Mode_Type :=
7743 Scope_Suppress.Overflow_Mode_Assertions;
7744 Svo : constant Boolean :=
7745 Scope_Suppress.Suppress (Overflow_Check);
7747 begin
7748 Scope_Suppress.Overflow_Mode_General := Strict;
7749 Scope_Suppress.Overflow_Mode_Assertions := Strict;
7751 if Suppress then
7752 Scope_Suppress.Suppress (Overflow_Check) := True;
7753 end if;
7755 Analyze_And_Resolve (N, Typ);
7757 Scope_Suppress.Suppress (Overflow_Check) := Svo;
7758 Scope_Suppress.Overflow_Mode_General := Svg;
7759 Scope_Suppress.Overflow_Mode_Assertions := Sva;
7760 end Reanalyze;
7762 --------------
7763 -- Reexpand --
7764 --------------
7766 procedure Reexpand (Suppress : Boolean := False) is
7767 Svg : constant Overflow_Mode_Type :=
7768 Scope_Suppress.Overflow_Mode_General;
7769 Sva : constant Overflow_Mode_Type :=
7770 Scope_Suppress.Overflow_Mode_Assertions;
7771 Svo : constant Boolean :=
7772 Scope_Suppress.Suppress (Overflow_Check);
7774 begin
7775 Scope_Suppress.Overflow_Mode_General := Strict;
7776 Scope_Suppress.Overflow_Mode_Assertions := Strict;
7777 Set_Analyzed (N, False);
7779 if Suppress then
7780 Scope_Suppress.Suppress (Overflow_Check) := True;
7781 end if;
7783 Expand (N);
7785 Scope_Suppress.Suppress (Overflow_Check) := Svo;
7786 Scope_Suppress.Overflow_Mode_General := Svg;
7787 Scope_Suppress.Overflow_Mode_Assertions := Sva;
7788 end Reexpand;
7790 -- Start of processing for Minimize_Eliminate_Overflows
7792 begin
7793 -- Case where we do not have a signed integer arithmetic operation
7795 if not Is_Signed_Integer_Arithmetic_Op (N) then
7797 -- Use the normal Determine_Range routine to get the range. We
7798 -- don't require operands to be valid, invalid values may result in
7799 -- rubbish results where the result has not been properly checked for
7800 -- overflow, that's fine.
7802 Determine_Range (N, OK, Lo, Hi, Assume_Valid => False);
7804 -- If Determine_Range did not work (can this in fact happen? Not
7805 -- clear but might as well protect), use type bounds.
7807 if not OK then
7808 Lo := Intval (Type_Low_Bound (Base_Type (Etype (N))));
7809 Hi := Intval (Type_High_Bound (Base_Type (Etype (N))));
7810 end if;
7812 -- If we don't have a binary operator, all we have to do is to set
7813 -- the Hi/Lo range, so we are done.
7815 return;
7817 -- Processing for if expression
7819 elsif Nkind (N) = N_If_Expression then
7820 declare
7821 Then_DE : constant Node_Id := Next (First (Expressions (N)));
7822 Else_DE : constant Node_Id := Next (Then_DE);
7824 begin
7825 Bignum_Operands := False;
7827 Minimize_Eliminate_Overflows
7828 (Then_DE, Lo, Hi, Top_Level => False);
7830 if Lo = No_Uint then
7831 Bignum_Operands := True;
7832 end if;
7834 Minimize_Eliminate_Overflows
7835 (Else_DE, Rlo, Rhi, Top_Level => False);
7837 if Rlo = No_Uint then
7838 Bignum_Operands := True;
7839 else
7840 Long_Long_Integer_Operands :=
7841 Etype (Then_DE) = LLIB or else Etype (Else_DE) = LLIB;
7843 Min (Lo, Rlo);
7844 Max (Hi, Rhi);
7845 end if;
7847 -- If at least one of our operands is now Bignum, we must rebuild
7848 -- the if expression to use Bignum operands. We will analyze the
7849 -- rebuilt if expression with overflow checks off, since once we
7850 -- are in bignum mode, we are all done with overflow checks.
7852 if Bignum_Operands then
7853 Rewrite (N,
7854 Make_If_Expression (Loc,
7855 Expressions => New_List (
7856 Remove_Head (Expressions (N)),
7857 Convert_To_Bignum (Then_DE),
7858 Convert_To_Bignum (Else_DE)),
7859 Is_Elsif => Is_Elsif (N)));
7861 Reanalyze (RTE (RE_Bignum), Suppress => True);
7863 -- If we have no Long_Long_Integer operands, then we are in result
7864 -- range, since it means that none of our operands felt the need
7865 -- to worry about overflow (otherwise it would have already been
7866 -- converted to long long integer or bignum). We reexpand to
7867 -- complete the expansion of the if expression (but we do not
7868 -- need to reanalyze).
7870 elsif not Long_Long_Integer_Operands then
7871 Set_Do_Overflow_Check (N, False);
7872 Reexpand;
7874 -- Otherwise convert us to long long integer mode. Note that we
7875 -- don't need any further overflow checking at this level.
7877 else
7878 Convert_To_And_Rewrite (LLIB, Then_DE);
7879 Convert_To_And_Rewrite (LLIB, Else_DE);
7880 Set_Etype (N, LLIB);
7882 -- Now reanalyze with overflow checks off
7884 Set_Do_Overflow_Check (N, False);
7885 Reanalyze (LLIB, Suppress => True);
7886 end if;
7887 end;
7889 return;
7891 -- Here for case expression
7893 elsif Nkind (N) = N_Case_Expression then
7894 Bignum_Operands := False;
7895 Long_Long_Integer_Operands := False;
7897 declare
7898 Alt : Node_Id;
7900 begin
7901 -- Loop through expressions applying recursive call
7903 Alt := First (Alternatives (N));
7904 while Present (Alt) loop
7905 declare
7906 Aexp : constant Node_Id := Expression (Alt);
7908 begin
7909 Minimize_Eliminate_Overflows
7910 (Aexp, Lo, Hi, Top_Level => False);
7912 if Lo = No_Uint then
7913 Bignum_Operands := True;
7914 elsif Etype (Aexp) = LLIB then
7915 Long_Long_Integer_Operands := True;
7916 end if;
7917 end;
7919 Next (Alt);
7920 end loop;
7922 -- If we have no bignum or long long integer operands, it means
7923 -- that none of our dependent expressions could raise overflow.
7924 -- In this case, we simply return with no changes except for
7925 -- resetting the overflow flag, since we are done with overflow
7926 -- checks for this node. We will reexpand to get the needed
7927 -- expansion for the case expression, but we do not need to
7928 -- reanalyze, since nothing has changed.
7930 if not (Bignum_Operands or Long_Long_Integer_Operands) then
7931 Set_Do_Overflow_Check (N, False);
7932 Reexpand (Suppress => True);
7934 -- Otherwise we are going to rebuild the case expression using
7935 -- either bignum or long long integer operands throughout.
7937 else
7938 declare
7939 Rtype : Entity_Id;
7940 New_Alts : List_Id;
7941 New_Exp : Node_Id;
7943 begin
7944 New_Alts := New_List;
7945 Alt := First (Alternatives (N));
7946 while Present (Alt) loop
7947 if Bignum_Operands then
7948 New_Exp := Convert_To_Bignum (Expression (Alt));
7949 Rtype := RTE (RE_Bignum);
7950 else
7951 New_Exp := Convert_To (LLIB, Expression (Alt));
7952 Rtype := LLIB;
7953 end if;
7955 Append_To (New_Alts,
7956 Make_Case_Expression_Alternative (Sloc (Alt),
7957 Actions => No_List,
7958 Discrete_Choices => Discrete_Choices (Alt),
7959 Expression => New_Exp));
7961 Next (Alt);
7962 end loop;
7964 Rewrite (N,
7965 Make_Case_Expression (Loc,
7966 Expression => Expression (N),
7967 Alternatives => New_Alts));
7969 Reanalyze (Rtype, Suppress => True);
7970 end;
7971 end if;
7972 end;
7974 return;
7975 end if;
7977 -- If we have an arithmetic operator we make recursive calls on the
7978 -- operands to get the ranges (and to properly process the subtree
7979 -- that lies below us).
7981 Minimize_Eliminate_Overflows
7982 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
7984 if Binary then
7985 Minimize_Eliminate_Overflows
7986 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
7987 end if;
7989 -- Record if we have Long_Long_Integer operands
7991 Long_Long_Integer_Operands :=
7992 Etype (Right_Opnd (N)) = LLIB
7993 or else (Binary and then Etype (Left_Opnd (N)) = LLIB);
7995 -- If either operand is a bignum, then result will be a bignum and we
7996 -- don't need to do any range analysis. As previously discussed we could
7997 -- do range analysis in such cases, but it could mean working with giant
7998 -- numbers at compile time for very little gain (the number of cases
7999 -- in which we could slip back from bignum mode is small).
8001 if Rlo = No_Uint or else (Binary and then Llo = No_Uint) then
8002 Lo := No_Uint;
8003 Hi := No_Uint;
8004 Bignum_Operands := True;
8006 -- Otherwise compute result range
8008 else
8009 Bignum_Operands := False;
8011 case Nkind (N) is
8013 -- Absolute value
8015 when N_Op_Abs =>
8016 Lo := Uint_0;
8017 Hi := UI_Max (abs Rlo, abs Rhi);
8019 -- Addition
8021 when N_Op_Add =>
8022 Lo := Llo + Rlo;
8023 Hi := Lhi + Rhi;
8025 -- Division
8027 when N_Op_Divide =>
8029 -- If the right operand can only be zero, set 0..0
8031 if Rlo = 0 and then Rhi = 0 then
8032 Lo := Uint_0;
8033 Hi := Uint_0;
8035 -- Possible bounds of division must come from dividing end
8036 -- values of the input ranges (four possibilities), provided
8037 -- zero is not included in the possible values of the right
8038 -- operand.
8040 -- Otherwise, we just consider two intervals of values for
8041 -- the right operand: the interval of negative values (up to
8042 -- -1) and the interval of positive values (starting at 1).
8043 -- Since division by 1 is the identity, and division by -1
8044 -- is negation, we get all possible bounds of division in that
8045 -- case by considering:
8046 -- - all values from the division of end values of input
8047 -- ranges;
8048 -- - the end values of the left operand;
8049 -- - the negation of the end values of the left operand.
8051 else
8052 declare
8053 Mrk : constant Uintp.Save_Mark := Mark;
8054 -- Mark so we can release the RR and Ev values
8056 Ev1 : Uint;
8057 Ev2 : Uint;
8058 Ev3 : Uint;
8059 Ev4 : Uint;
8061 begin
8062 -- Discard extreme values of zero for the divisor, since
8063 -- they will simply result in an exception in any case.
8065 if Rlo = 0 then
8066 Rlo := Uint_1;
8067 elsif Rhi = 0 then
8068 Rhi := -Uint_1;
8069 end if;
8071 -- Compute possible bounds coming from dividing end
8072 -- values of the input ranges.
8074 Ev1 := Llo / Rlo;
8075 Ev2 := Llo / Rhi;
8076 Ev3 := Lhi / Rlo;
8077 Ev4 := Lhi / Rhi;
8079 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8080 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8082 -- If the right operand can be both negative or positive,
8083 -- include the end values of the left operand in the
8084 -- extreme values, as well as their negation.
8086 if Rlo < 0 and then Rhi > 0 then
8087 Ev1 := Llo;
8088 Ev2 := -Llo;
8089 Ev3 := Lhi;
8090 Ev4 := -Lhi;
8092 Min (Lo,
8093 UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4)));
8094 Max (Hi,
8095 UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4)));
8096 end if;
8098 -- Release the RR and Ev values
8100 Release_And_Save (Mrk, Lo, Hi);
8101 end;
8102 end if;
8104 -- Exponentiation
8106 when N_Op_Expon =>
8108 -- Discard negative values for the exponent, since they will
8109 -- simply result in an exception in any case.
8111 if Rhi < 0 then
8112 Rhi := Uint_0;
8113 elsif Rlo < 0 then
8114 Rlo := Uint_0;
8115 end if;
8117 -- Estimate number of bits in result before we go computing
8118 -- giant useless bounds. Basically the number of bits in the
8119 -- result is the number of bits in the base multiplied by the
8120 -- value of the exponent. If this is big enough that the result
8121 -- definitely won't fit in Long_Long_Integer, switch to bignum
8122 -- mode immediately, and avoid computing giant bounds.
8124 -- The comparison here is approximate, but conservative, it
8125 -- only clicks on cases that are sure to exceed the bounds.
8127 if Num_Bits (UI_Max (abs Llo, abs Lhi)) * Rhi + 1 > 100 then
8128 Lo := No_Uint;
8129 Hi := No_Uint;
8131 -- If right operand is zero then result is 1
8133 elsif Rhi = 0 then
8134 Lo := Uint_1;
8135 Hi := Uint_1;
8137 else
8138 -- High bound comes either from exponentiation of largest
8139 -- positive value to largest exponent value, or from
8140 -- the exponentiation of most negative value to an
8141 -- even exponent.
8143 declare
8144 Hi1, Hi2 : Uint;
8146 begin
8147 if Lhi > 0 then
8148 Hi1 := Lhi ** Rhi;
8149 else
8150 Hi1 := Uint_0;
8151 end if;
8153 if Llo < 0 then
8154 if Rhi mod 2 = 0 then
8155 Hi2 := Llo ** Rhi;
8156 else
8157 Hi2 := Llo ** (Rhi - 1);
8158 end if;
8159 else
8160 Hi2 := Uint_0;
8161 end if;
8163 Hi := UI_Max (Hi1, Hi2);
8164 end;
8166 -- Result can only be negative if base can be negative
8168 if Llo < 0 then
8169 if Rhi mod 2 = 0 then
8170 Lo := Llo ** (Rhi - 1);
8171 else
8172 Lo := Llo ** Rhi;
8173 end if;
8175 -- Otherwise low bound is minimum ** minimum
8177 else
8178 Lo := Llo ** Rlo;
8179 end if;
8180 end if;
8182 -- Negation
8184 when N_Op_Minus =>
8185 Lo := -Rhi;
8186 Hi := -Rlo;
8188 -- Mod
8190 when N_Op_Mod =>
8191 declare
8192 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8193 -- This is the maximum absolute value of the result
8195 begin
8196 Lo := Uint_0;
8197 Hi := Uint_0;
8199 -- The result depends only on the sign and magnitude of
8200 -- the right operand, it does not depend on the sign or
8201 -- magnitude of the left operand.
8203 if Rlo < 0 then
8204 Lo := -Maxabs;
8205 end if;
8207 if Rhi > 0 then
8208 Hi := Maxabs;
8209 end if;
8210 end;
8212 -- Multiplication
8214 when N_Op_Multiply =>
8216 -- Possible bounds of multiplication must come from multiplying
8217 -- end values of the input ranges (four possibilities).
8219 declare
8220 Mrk : constant Uintp.Save_Mark := Mark;
8221 -- Mark so we can release the Ev values
8223 Ev1 : constant Uint := Llo * Rlo;
8224 Ev2 : constant Uint := Llo * Rhi;
8225 Ev3 : constant Uint := Lhi * Rlo;
8226 Ev4 : constant Uint := Lhi * Rhi;
8228 begin
8229 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8230 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8232 -- Release the Ev values
8234 Release_And_Save (Mrk, Lo, Hi);
8235 end;
8237 -- Plus operator (affirmation)
8239 when N_Op_Plus =>
8240 Lo := Rlo;
8241 Hi := Rhi;
8243 -- Remainder
8245 when N_Op_Rem =>
8246 declare
8247 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8248 -- This is the maximum absolute value of the result. Note
8249 -- that the result range does not depend on the sign of the
8250 -- right operand.
8252 begin
8253 Lo := Uint_0;
8254 Hi := Uint_0;
8256 -- Case of left operand negative, which results in a range
8257 -- of -Maxabs .. 0 for those negative values. If there are
8258 -- no negative values then Lo value of result is always 0.
8260 if Llo < 0 then
8261 Lo := -Maxabs;
8262 end if;
8264 -- Case of left operand positive
8266 if Lhi > 0 then
8267 Hi := Maxabs;
8268 end if;
8269 end;
8271 -- Subtract
8273 when N_Op_Subtract =>
8274 Lo := Llo - Rhi;
8275 Hi := Lhi - Rlo;
8277 -- Nothing else should be possible
8279 when others =>
8280 raise Program_Error;
8281 end case;
8282 end if;
8284 -- Here for the case where we have not rewritten anything (no bignum
8285 -- operands or long long integer operands), and we know the result.
8286 -- If we know we are in the result range, and we do not have Bignum
8287 -- operands or Long_Long_Integer operands, we can just reexpand with
8288 -- overflow checks turned off (since we know we cannot have overflow).
8289 -- As always the reexpansion is required to complete expansion of the
8290 -- operator, but we do not need to reanalyze, and we prevent recursion
8291 -- by suppressing the check.
8293 if not (Bignum_Operands or Long_Long_Integer_Operands)
8294 and then In_Result_Range
8295 then
8296 Set_Do_Overflow_Check (N, False);
8297 Reexpand (Suppress => True);
8298 return;
8300 -- Here we know that we are not in the result range, and in the general
8301 -- case we will move into either the Bignum or Long_Long_Integer domain
8302 -- to compute the result. However, there is one exception. If we are
8303 -- at the top level, and we do not have Bignum or Long_Long_Integer
8304 -- operands, we will have to immediately convert the result back to
8305 -- the result type, so there is no point in Bignum/Long_Long_Integer
8306 -- fiddling.
8308 elsif Top_Level
8309 and then not (Bignum_Operands or Long_Long_Integer_Operands)
8311 -- One further refinement. If we are at the top level, but our parent
8312 -- is a type conversion, then go into bignum or long long integer node
8313 -- since the result will be converted to that type directly without
8314 -- going through the result type, and we may avoid an overflow. This
8315 -- is the case for example of Long_Long_Integer (A ** 4), where A is
8316 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
8317 -- but does not fit in Integer.
8319 and then Nkind (Parent (N)) /= N_Type_Conversion
8320 then
8321 -- Here keep original types, but we need to complete analysis
8323 -- One subtlety. We can't just go ahead and do an analyze operation
8324 -- here because it will cause recursion into the whole MINIMIZED/
8325 -- ELIMINATED overflow processing which is not what we want. Here
8326 -- we are at the top level, and we need a check against the result
8327 -- mode (i.e. we want to use STRICT mode). So do exactly that.
8328 -- Also, we have not modified the node, so this is a case where
8329 -- we need to reexpand, but not reanalyze.
8331 Reexpand;
8332 return;
8334 -- Cases where we do the operation in Bignum mode. This happens either
8335 -- because one of our operands is in Bignum mode already, or because
8336 -- the computed bounds are outside the bounds of Long_Long_Integer,
8337 -- which in some cases can be indicated by Hi and Lo being No_Uint.
8339 -- Note: we could do better here and in some cases switch back from
8340 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
8341 -- 0 .. 1, but the cases are rare and it is not worth the effort.
8342 -- Failing to do this switching back is only an efficiency issue.
8344 elsif Lo = No_Uint or else Lo < LLLo or else Hi > LLHi then
8346 -- OK, we are definitely outside the range of Long_Long_Integer. The
8347 -- question is whether to move to Bignum mode, or stay in the domain
8348 -- of Long_Long_Integer, signalling that an overflow check is needed.
8350 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
8351 -- the Bignum business. In ELIMINATED mode, we will normally move
8352 -- into Bignum mode, but there is an exception if neither of our
8353 -- operands is Bignum now, and we are at the top level (Top_Level
8354 -- set True). In this case, there is no point in moving into Bignum
8355 -- mode to prevent overflow if the caller will immediately convert
8356 -- the Bignum value back to LLI with an overflow check. It's more
8357 -- efficient to stay in LLI mode with an overflow check (if needed)
8359 if Check_Mode = Minimized
8360 or else (Top_Level and not Bignum_Operands)
8361 then
8362 if Do_Overflow_Check (N) then
8363 Enable_Overflow_Check (N);
8364 end if;
8366 -- The result now has to be in Long_Long_Integer mode, so adjust
8367 -- the possible range to reflect this. Note these calls also
8368 -- change No_Uint values from the top level case to LLI bounds.
8370 Max (Lo, LLLo);
8371 Min (Hi, LLHi);
8373 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
8375 else
8376 pragma Assert (Check_Mode = Eliminated);
8378 declare
8379 Fent : Entity_Id;
8380 Args : List_Id;
8382 begin
8383 case Nkind (N) is
8384 when N_Op_Abs =>
8385 Fent := RTE (RE_Big_Abs);
8387 when N_Op_Add =>
8388 Fent := RTE (RE_Big_Add);
8390 when N_Op_Divide =>
8391 Fent := RTE (RE_Big_Div);
8393 when N_Op_Expon =>
8394 Fent := RTE (RE_Big_Exp);
8396 when N_Op_Minus =>
8397 Fent := RTE (RE_Big_Neg);
8399 when N_Op_Mod =>
8400 Fent := RTE (RE_Big_Mod);
8402 when N_Op_Multiply =>
8403 Fent := RTE (RE_Big_Mul);
8405 when N_Op_Rem =>
8406 Fent := RTE (RE_Big_Rem);
8408 when N_Op_Subtract =>
8409 Fent := RTE (RE_Big_Sub);
8411 -- Anything else is an internal error, this includes the
8412 -- N_Op_Plus case, since how can plus cause the result
8413 -- to be out of range if the operand is in range?
8415 when others =>
8416 raise Program_Error;
8417 end case;
8419 -- Construct argument list for Bignum call, converting our
8420 -- operands to Bignum form if they are not already there.
8422 Args := New_List;
8424 if Binary then
8425 Append_To (Args, Convert_To_Bignum (Left_Opnd (N)));
8426 end if;
8428 Append_To (Args, Convert_To_Bignum (Right_Opnd (N)));
8430 -- Now rewrite the arithmetic operator with a call to the
8431 -- corresponding bignum function.
8433 Rewrite (N,
8434 Make_Function_Call (Loc,
8435 Name => New_Occurrence_Of (Fent, Loc),
8436 Parameter_Associations => Args));
8437 Reanalyze (RTE (RE_Bignum), Suppress => True);
8439 -- Indicate result is Bignum mode
8441 Lo := No_Uint;
8442 Hi := No_Uint;
8443 return;
8444 end;
8445 end if;
8447 -- Otherwise we are in range of Long_Long_Integer, so no overflow
8448 -- check is required, at least not yet.
8450 else
8451 Set_Do_Overflow_Check (N, False);
8452 end if;
8454 -- Here we are not in Bignum territory, but we may have long long
8455 -- integer operands that need special handling. First a special check:
8456 -- If an exponentiation operator exponent is of type Long_Long_Integer,
8457 -- it means we converted it to prevent overflow, but exponentiation
8458 -- requires a Natural right operand, so convert it back to Natural.
8459 -- This conversion may raise an exception which is fine.
8461 if Nkind (N) = N_Op_Expon and then Etype (Right_Opnd (N)) = LLIB then
8462 Convert_To_And_Rewrite (Standard_Natural, Right_Opnd (N));
8463 end if;
8465 -- Here we will do the operation in Long_Long_Integer. We do this even
8466 -- if we know an overflow check is required, better to do this in long
8467 -- long integer mode, since we are less likely to overflow.
8469 -- Convert right or only operand to Long_Long_Integer, except that
8470 -- we do not touch the exponentiation right operand.
8472 if Nkind (N) /= N_Op_Expon then
8473 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
8474 end if;
8476 -- Convert left operand to Long_Long_Integer for binary case
8478 if Binary then
8479 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
8480 end if;
8482 -- Reset node to unanalyzed
8484 Set_Analyzed (N, False);
8485 Set_Etype (N, Empty);
8486 Set_Entity (N, Empty);
8488 -- Now analyze this new node. This reanalysis will complete processing
8489 -- for the node. In particular we will complete the expansion of an
8490 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
8491 -- we will complete any division checks (since we have not changed the
8492 -- setting of the Do_Division_Check flag).
8494 -- We do this reanalysis in STRICT mode to avoid recursion into the
8495 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
8497 declare
8498 SG : constant Overflow_Mode_Type :=
8499 Scope_Suppress.Overflow_Mode_General;
8500 SA : constant Overflow_Mode_Type :=
8501 Scope_Suppress.Overflow_Mode_Assertions;
8503 begin
8504 Scope_Suppress.Overflow_Mode_General := Strict;
8505 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8507 if not Do_Overflow_Check (N) then
8508 Reanalyze (LLIB, Suppress => True);
8509 else
8510 Reanalyze (LLIB);
8511 end if;
8513 Scope_Suppress.Overflow_Mode_General := SG;
8514 Scope_Suppress.Overflow_Mode_Assertions := SA;
8515 end;
8516 end Minimize_Eliminate_Overflows;
8518 -------------------------
8519 -- Overflow_Check_Mode --
8520 -------------------------
8522 function Overflow_Check_Mode return Overflow_Mode_Type is
8523 begin
8524 if In_Assertion_Expr = 0 then
8525 return Scope_Suppress.Overflow_Mode_General;
8526 else
8527 return Scope_Suppress.Overflow_Mode_Assertions;
8528 end if;
8529 end Overflow_Check_Mode;
8531 --------------------------------
8532 -- Overflow_Checks_Suppressed --
8533 --------------------------------
8535 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
8536 begin
8537 if Present (E) and then Checks_May_Be_Suppressed (E) then
8538 return Is_Check_Suppressed (E, Overflow_Check);
8539 else
8540 return Scope_Suppress.Suppress (Overflow_Check);
8541 end if;
8542 end Overflow_Checks_Suppressed;
8544 ---------------------------------
8545 -- Predicate_Checks_Suppressed --
8546 ---------------------------------
8548 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean is
8549 begin
8550 if Present (E) and then Checks_May_Be_Suppressed (E) then
8551 return Is_Check_Suppressed (E, Predicate_Check);
8552 else
8553 return Scope_Suppress.Suppress (Predicate_Check);
8554 end if;
8555 end Predicate_Checks_Suppressed;
8557 -----------------------------
8558 -- Range_Checks_Suppressed --
8559 -----------------------------
8561 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
8562 begin
8563 if Present (E) then
8564 if Kill_Range_Checks (E) then
8565 return True;
8567 elsif Checks_May_Be_Suppressed (E) then
8568 return Is_Check_Suppressed (E, Range_Check);
8569 end if;
8570 end if;
8572 return Scope_Suppress.Suppress (Range_Check);
8573 end Range_Checks_Suppressed;
8575 -----------------------------------------
8576 -- Range_Or_Validity_Checks_Suppressed --
8577 -----------------------------------------
8579 -- Note: the coding would be simpler here if we simply made appropriate
8580 -- calls to Range/Validity_Checks_Suppressed, but that would result in
8581 -- duplicated checks which we prefer to avoid.
8583 function Range_Or_Validity_Checks_Suppressed
8584 (Expr : Node_Id) return Boolean
8586 begin
8587 -- Immediate return if scope checks suppressed for either check
8589 if Scope_Suppress.Suppress (Range_Check)
8591 Scope_Suppress.Suppress (Validity_Check)
8592 then
8593 return True;
8594 end if;
8596 -- If no expression, that's odd, decide that checks are suppressed,
8597 -- since we don't want anyone trying to do checks in this case, which
8598 -- is most likely the result of some other error.
8600 if No (Expr) then
8601 return True;
8602 end if;
8604 -- Expression is present, so perform suppress checks on type
8606 declare
8607 Typ : constant Entity_Id := Etype (Expr);
8608 begin
8609 if Checks_May_Be_Suppressed (Typ)
8610 and then (Is_Check_Suppressed (Typ, Range_Check)
8611 or else
8612 Is_Check_Suppressed (Typ, Validity_Check))
8613 then
8614 return True;
8615 end if;
8616 end;
8618 -- If expression is an entity name, perform checks on this entity
8620 if Is_Entity_Name (Expr) then
8621 declare
8622 Ent : constant Entity_Id := Entity (Expr);
8623 begin
8624 if Checks_May_Be_Suppressed (Ent) then
8625 return Is_Check_Suppressed (Ent, Range_Check)
8626 or else Is_Check_Suppressed (Ent, Validity_Check);
8627 end if;
8628 end;
8629 end if;
8631 -- If we fall through, no checks suppressed
8633 return False;
8634 end Range_Or_Validity_Checks_Suppressed;
8636 -------------------
8637 -- Remove_Checks --
8638 -------------------
8640 procedure Remove_Checks (Expr : Node_Id) is
8641 function Process (N : Node_Id) return Traverse_Result;
8642 -- Process a single node during the traversal
8644 procedure Traverse is new Traverse_Proc (Process);
8645 -- The traversal procedure itself
8647 -------------
8648 -- Process --
8649 -------------
8651 function Process (N : Node_Id) return Traverse_Result is
8652 begin
8653 if Nkind (N) not in N_Subexpr then
8654 return Skip;
8655 end if;
8657 Set_Do_Range_Check (N, False);
8659 case Nkind (N) is
8660 when N_And_Then =>
8661 Traverse (Left_Opnd (N));
8662 return Skip;
8664 when N_Attribute_Reference =>
8665 Set_Do_Overflow_Check (N, False);
8667 when N_Function_Call =>
8668 Set_Do_Tag_Check (N, False);
8670 when N_Op =>
8671 Set_Do_Overflow_Check (N, False);
8673 case Nkind (N) is
8674 when N_Op_Divide =>
8675 Set_Do_Division_Check (N, False);
8677 when N_Op_And =>
8678 Set_Do_Length_Check (N, False);
8680 when N_Op_Mod =>
8681 Set_Do_Division_Check (N, False);
8683 when N_Op_Or =>
8684 Set_Do_Length_Check (N, False);
8686 when N_Op_Rem =>
8687 Set_Do_Division_Check (N, False);
8689 when N_Op_Xor =>
8690 Set_Do_Length_Check (N, False);
8692 when others =>
8693 null;
8694 end case;
8696 when N_Or_Else =>
8697 Traverse (Left_Opnd (N));
8698 return Skip;
8700 when N_Selected_Component =>
8701 Set_Do_Discriminant_Check (N, False);
8703 when N_Type_Conversion =>
8704 Set_Do_Length_Check (N, False);
8705 Set_Do_Tag_Check (N, False);
8706 Set_Do_Overflow_Check (N, False);
8708 when others =>
8709 null;
8710 end case;
8712 return OK;
8713 end Process;
8715 -- Start of processing for Remove_Checks
8717 begin
8718 Traverse (Expr);
8719 end Remove_Checks;
8721 ----------------------------
8722 -- Selected_Length_Checks --
8723 ----------------------------
8725 function Selected_Length_Checks
8726 (Ck_Node : Node_Id;
8727 Target_Typ : Entity_Id;
8728 Source_Typ : Entity_Id;
8729 Warn_Node : Node_Id) return Check_Result
8731 Loc : constant Source_Ptr := Sloc (Ck_Node);
8732 S_Typ : Entity_Id;
8733 T_Typ : Entity_Id;
8734 Expr_Actual : Node_Id;
8735 Exptyp : Entity_Id;
8736 Cond : Node_Id := Empty;
8737 Do_Access : Boolean := False;
8738 Wnode : Node_Id := Warn_Node;
8739 Ret_Result : Check_Result := (Empty, Empty);
8740 Num_Checks : Natural := 0;
8742 procedure Add_Check (N : Node_Id);
8743 -- Adds the action given to Ret_Result if N is non-Empty
8745 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
8746 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
8747 -- Comments required ???
8749 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
8750 -- True for equal literals and for nodes that denote the same constant
8751 -- entity, even if its value is not a static constant. This includes the
8752 -- case of a discriminal reference within an init proc. Removes some
8753 -- obviously superfluous checks.
8755 function Length_E_Cond
8756 (Exptyp : Entity_Id;
8757 Typ : Entity_Id;
8758 Indx : Nat) return Node_Id;
8759 -- Returns expression to compute:
8760 -- Typ'Length /= Exptyp'Length
8762 function Length_N_Cond
8763 (Expr : Node_Id;
8764 Typ : Entity_Id;
8765 Indx : Nat) return Node_Id;
8766 -- Returns expression to compute:
8767 -- Typ'Length /= Expr'Length
8769 ---------------
8770 -- Add_Check --
8771 ---------------
8773 procedure Add_Check (N : Node_Id) is
8774 begin
8775 if Present (N) then
8777 -- For now, ignore attempt to place more than two checks ???
8778 -- This is really worrisome, are we really discarding checks ???
8780 if Num_Checks = 2 then
8781 return;
8782 end if;
8784 pragma Assert (Num_Checks <= 1);
8785 Num_Checks := Num_Checks + 1;
8786 Ret_Result (Num_Checks) := N;
8787 end if;
8788 end Add_Check;
8790 ------------------
8791 -- Get_E_Length --
8792 ------------------
8794 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
8795 SE : constant Entity_Id := Scope (E);
8796 N : Node_Id;
8797 E1 : Entity_Id := E;
8799 begin
8800 if Ekind (Scope (E)) = E_Record_Type
8801 and then Has_Discriminants (Scope (E))
8802 then
8803 N := Build_Discriminal_Subtype_Of_Component (E);
8805 if Present (N) then
8806 Insert_Action (Ck_Node, N);
8807 E1 := Defining_Identifier (N);
8808 end if;
8809 end if;
8811 if Ekind (E1) = E_String_Literal_Subtype then
8812 return
8813 Make_Integer_Literal (Loc,
8814 Intval => String_Literal_Length (E1));
8816 elsif SE /= Standard_Standard
8817 and then Ekind (Scope (SE)) = E_Protected_Type
8818 and then Has_Discriminants (Scope (SE))
8819 and then Has_Completion (Scope (SE))
8820 and then not Inside_Init_Proc
8821 then
8822 -- If the type whose length is needed is a private component
8823 -- constrained by a discriminant, we must expand the 'Length
8824 -- attribute into an explicit computation, using the discriminal
8825 -- of the current protected operation. This is because the actual
8826 -- type of the prival is constructed after the protected opera-
8827 -- tion has been fully expanded.
8829 declare
8830 Indx_Type : Node_Id;
8831 Lo : Node_Id;
8832 Hi : Node_Id;
8833 Do_Expand : Boolean := False;
8835 begin
8836 Indx_Type := First_Index (E);
8838 for J in 1 .. Indx - 1 loop
8839 Next_Index (Indx_Type);
8840 end loop;
8842 Get_Index_Bounds (Indx_Type, Lo, Hi);
8844 if Nkind (Lo) = N_Identifier
8845 and then Ekind (Entity (Lo)) = E_In_Parameter
8846 then
8847 Lo := Get_Discriminal (E, Lo);
8848 Do_Expand := True;
8849 end if;
8851 if Nkind (Hi) = N_Identifier
8852 and then Ekind (Entity (Hi)) = E_In_Parameter
8853 then
8854 Hi := Get_Discriminal (E, Hi);
8855 Do_Expand := True;
8856 end if;
8858 if Do_Expand then
8859 if not Is_Entity_Name (Lo) then
8860 Lo := Duplicate_Subexpr_No_Checks (Lo);
8861 end if;
8863 if not Is_Entity_Name (Hi) then
8864 Lo := Duplicate_Subexpr_No_Checks (Hi);
8865 end if;
8867 N :=
8868 Make_Op_Add (Loc,
8869 Left_Opnd =>
8870 Make_Op_Subtract (Loc,
8871 Left_Opnd => Hi,
8872 Right_Opnd => Lo),
8874 Right_Opnd => Make_Integer_Literal (Loc, 1));
8875 return N;
8877 else
8878 N :=
8879 Make_Attribute_Reference (Loc,
8880 Attribute_Name => Name_Length,
8881 Prefix =>
8882 New_Occurrence_Of (E1, Loc));
8884 if Indx > 1 then
8885 Set_Expressions (N, New_List (
8886 Make_Integer_Literal (Loc, Indx)));
8887 end if;
8889 return N;
8890 end if;
8891 end;
8893 else
8894 N :=
8895 Make_Attribute_Reference (Loc,
8896 Attribute_Name => Name_Length,
8897 Prefix =>
8898 New_Occurrence_Of (E1, Loc));
8900 if Indx > 1 then
8901 Set_Expressions (N, New_List (
8902 Make_Integer_Literal (Loc, Indx)));
8903 end if;
8905 return N;
8906 end if;
8907 end Get_E_Length;
8909 ------------------
8910 -- Get_N_Length --
8911 ------------------
8913 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
8914 begin
8915 return
8916 Make_Attribute_Reference (Loc,
8917 Attribute_Name => Name_Length,
8918 Prefix =>
8919 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
8920 Expressions => New_List (
8921 Make_Integer_Literal (Loc, Indx)));
8922 end Get_N_Length;
8924 -------------------
8925 -- Length_E_Cond --
8926 -------------------
8928 function Length_E_Cond
8929 (Exptyp : Entity_Id;
8930 Typ : Entity_Id;
8931 Indx : Nat) return Node_Id
8933 begin
8934 return
8935 Make_Op_Ne (Loc,
8936 Left_Opnd => Get_E_Length (Typ, Indx),
8937 Right_Opnd => Get_E_Length (Exptyp, Indx));
8938 end Length_E_Cond;
8940 -------------------
8941 -- Length_N_Cond --
8942 -------------------
8944 function Length_N_Cond
8945 (Expr : Node_Id;
8946 Typ : Entity_Id;
8947 Indx : Nat) return Node_Id
8949 begin
8950 return
8951 Make_Op_Ne (Loc,
8952 Left_Opnd => Get_E_Length (Typ, Indx),
8953 Right_Opnd => Get_N_Length (Expr, Indx));
8954 end Length_N_Cond;
8956 -----------------
8957 -- Same_Bounds --
8958 -----------------
8960 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
8961 begin
8962 return
8963 (Nkind (L) = N_Integer_Literal
8964 and then Nkind (R) = N_Integer_Literal
8965 and then Intval (L) = Intval (R))
8967 or else
8968 (Is_Entity_Name (L)
8969 and then Ekind (Entity (L)) = E_Constant
8970 and then ((Is_Entity_Name (R)
8971 and then Entity (L) = Entity (R))
8972 or else
8973 (Nkind (R) = N_Type_Conversion
8974 and then Is_Entity_Name (Expression (R))
8975 and then Entity (L) = Entity (Expression (R)))))
8977 or else
8978 (Is_Entity_Name (R)
8979 and then Ekind (Entity (R)) = E_Constant
8980 and then Nkind (L) = N_Type_Conversion
8981 and then Is_Entity_Name (Expression (L))
8982 and then Entity (R) = Entity (Expression (L)))
8984 or else
8985 (Is_Entity_Name (L)
8986 and then Is_Entity_Name (R)
8987 and then Entity (L) = Entity (R)
8988 and then Ekind (Entity (L)) = E_In_Parameter
8989 and then Inside_Init_Proc);
8990 end Same_Bounds;
8992 -- Start of processing for Selected_Length_Checks
8994 begin
8995 if not Expander_Active then
8996 return Ret_Result;
8997 end if;
8999 if Target_Typ = Any_Type
9000 or else Target_Typ = Any_Composite
9001 or else Raises_Constraint_Error (Ck_Node)
9002 then
9003 return Ret_Result;
9004 end if;
9006 if No (Wnode) then
9007 Wnode := Ck_Node;
9008 end if;
9010 T_Typ := Target_Typ;
9012 if No (Source_Typ) then
9013 S_Typ := Etype (Ck_Node);
9014 else
9015 S_Typ := Source_Typ;
9016 end if;
9018 if S_Typ = Any_Type or else S_Typ = Any_Composite then
9019 return Ret_Result;
9020 end if;
9022 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
9023 S_Typ := Designated_Type (S_Typ);
9024 T_Typ := Designated_Type (T_Typ);
9025 Do_Access := True;
9027 -- A simple optimization for the null case
9029 if Known_Null (Ck_Node) then
9030 return Ret_Result;
9031 end if;
9032 end if;
9034 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
9035 if Is_Constrained (T_Typ) then
9037 -- The checking code to be generated will freeze the corresponding
9038 -- array type. However, we must freeze the type now, so that the
9039 -- freeze node does not appear within the generated if expression,
9040 -- but ahead of it.
9042 Freeze_Before (Ck_Node, T_Typ);
9044 Expr_Actual := Get_Referenced_Object (Ck_Node);
9045 Exptyp := Get_Actual_Subtype (Ck_Node);
9047 if Is_Access_Type (Exptyp) then
9048 Exptyp := Designated_Type (Exptyp);
9049 end if;
9051 -- String_Literal case. This needs to be handled specially be-
9052 -- cause no index types are available for string literals. The
9053 -- condition is simply:
9055 -- T_Typ'Length = string-literal-length
9057 if Nkind (Expr_Actual) = N_String_Literal
9058 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
9059 then
9060 Cond :=
9061 Make_Op_Ne (Loc,
9062 Left_Opnd => Get_E_Length (T_Typ, 1),
9063 Right_Opnd =>
9064 Make_Integer_Literal (Loc,
9065 Intval =>
9066 String_Literal_Length (Etype (Expr_Actual))));
9068 -- General array case. Here we have a usable actual subtype for
9069 -- the expression, and the condition is built from the two types
9070 -- (Do_Length):
9072 -- T_Typ'Length /= Exptyp'Length or else
9073 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
9074 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
9075 -- ...
9077 elsif Is_Constrained (Exptyp) then
9078 declare
9079 Ndims : constant Nat := Number_Dimensions (T_Typ);
9081 L_Index : Node_Id;
9082 R_Index : Node_Id;
9083 L_Low : Node_Id;
9084 L_High : Node_Id;
9085 R_Low : Node_Id;
9086 R_High : Node_Id;
9087 L_Length : Uint;
9088 R_Length : Uint;
9089 Ref_Node : Node_Id;
9091 begin
9092 -- At the library level, we need to ensure that the type of
9093 -- the object is elaborated before the check itself is
9094 -- emitted. This is only done if the object is in the
9095 -- current compilation unit, otherwise the type is frozen
9096 -- and elaborated in its unit.
9098 if Is_Itype (Exptyp)
9099 and then
9100 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
9101 and then
9102 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
9103 and then In_Open_Scopes (Scope (Exptyp))
9104 then
9105 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
9106 Set_Itype (Ref_Node, Exptyp);
9107 Insert_Action (Ck_Node, Ref_Node);
9108 end if;
9110 L_Index := First_Index (T_Typ);
9111 R_Index := First_Index (Exptyp);
9113 for Indx in 1 .. Ndims loop
9114 if not (Nkind (L_Index) = N_Raise_Constraint_Error
9115 or else
9116 Nkind (R_Index) = N_Raise_Constraint_Error)
9117 then
9118 Get_Index_Bounds (L_Index, L_Low, L_High);
9119 Get_Index_Bounds (R_Index, R_Low, R_High);
9121 -- Deal with compile time length check. Note that we
9122 -- skip this in the access case, because the access
9123 -- value may be null, so we cannot know statically.
9125 if not Do_Access
9126 and then Compile_Time_Known_Value (L_Low)
9127 and then Compile_Time_Known_Value (L_High)
9128 and then Compile_Time_Known_Value (R_Low)
9129 and then Compile_Time_Known_Value (R_High)
9130 then
9131 if Expr_Value (L_High) >= Expr_Value (L_Low) then
9132 L_Length := Expr_Value (L_High) -
9133 Expr_Value (L_Low) + 1;
9134 else
9135 L_Length := UI_From_Int (0);
9136 end if;
9138 if Expr_Value (R_High) >= Expr_Value (R_Low) then
9139 R_Length := Expr_Value (R_High) -
9140 Expr_Value (R_Low) + 1;
9141 else
9142 R_Length := UI_From_Int (0);
9143 end if;
9145 if L_Length > R_Length then
9146 Add_Check
9147 (Compile_Time_Constraint_Error
9148 (Wnode, "too few elements for}??", T_Typ));
9150 elsif L_Length < R_Length then
9151 Add_Check
9152 (Compile_Time_Constraint_Error
9153 (Wnode, "too many elements for}??", T_Typ));
9154 end if;
9156 -- The comparison for an individual index subtype
9157 -- is omitted if the corresponding index subtypes
9158 -- statically match, since the result is known to
9159 -- be true. Note that this test is worth while even
9160 -- though we do static evaluation, because non-static
9161 -- subtypes can statically match.
9163 elsif not
9164 Subtypes_Statically_Match
9165 (Etype (L_Index), Etype (R_Index))
9167 and then not
9168 (Same_Bounds (L_Low, R_Low)
9169 and then Same_Bounds (L_High, R_High))
9170 then
9171 Evolve_Or_Else
9172 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
9173 end if;
9175 Next (L_Index);
9176 Next (R_Index);
9177 end if;
9178 end loop;
9179 end;
9181 -- Handle cases where we do not get a usable actual subtype that
9182 -- is constrained. This happens for example in the function call
9183 -- and explicit dereference cases. In these cases, we have to get
9184 -- the length or range from the expression itself, making sure we
9185 -- do not evaluate it more than once.
9187 -- Here Ck_Node is the original expression, or more properly the
9188 -- result of applying Duplicate_Expr to the original tree, forcing
9189 -- the result to be a name.
9191 else
9192 declare
9193 Ndims : constant Nat := Number_Dimensions (T_Typ);
9195 begin
9196 -- Build the condition for the explicit dereference case
9198 for Indx in 1 .. Ndims loop
9199 Evolve_Or_Else
9200 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
9201 end loop;
9202 end;
9203 end if;
9204 end if;
9205 end if;
9207 -- Construct the test and insert into the tree
9209 if Present (Cond) then
9210 if Do_Access then
9211 Cond := Guard_Access (Cond, Loc, Ck_Node);
9212 end if;
9214 Add_Check
9215 (Make_Raise_Constraint_Error (Loc,
9216 Condition => Cond,
9217 Reason => CE_Length_Check_Failed));
9218 end if;
9220 return Ret_Result;
9221 end Selected_Length_Checks;
9223 ---------------------------
9224 -- Selected_Range_Checks --
9225 ---------------------------
9227 function Selected_Range_Checks
9228 (Ck_Node : Node_Id;
9229 Target_Typ : Entity_Id;
9230 Source_Typ : Entity_Id;
9231 Warn_Node : Node_Id) return Check_Result
9233 Loc : constant Source_Ptr := Sloc (Ck_Node);
9234 S_Typ : Entity_Id;
9235 T_Typ : Entity_Id;
9236 Expr_Actual : Node_Id;
9237 Exptyp : Entity_Id;
9238 Cond : Node_Id := Empty;
9239 Do_Access : Boolean := False;
9240 Wnode : Node_Id := Warn_Node;
9241 Ret_Result : Check_Result := (Empty, Empty);
9242 Num_Checks : Integer := 0;
9244 procedure Add_Check (N : Node_Id);
9245 -- Adds the action given to Ret_Result if N is non-Empty
9247 function Discrete_Range_Cond
9248 (Expr : Node_Id;
9249 Typ : Entity_Id) return Node_Id;
9250 -- Returns expression to compute:
9251 -- Low_Bound (Expr) < Typ'First
9252 -- or else
9253 -- High_Bound (Expr) > Typ'Last
9255 function Discrete_Expr_Cond
9256 (Expr : Node_Id;
9257 Typ : Entity_Id) return Node_Id;
9258 -- Returns expression to compute:
9259 -- Expr < Typ'First
9260 -- or else
9261 -- Expr > Typ'Last
9263 function Get_E_First_Or_Last
9264 (Loc : Source_Ptr;
9265 E : Entity_Id;
9266 Indx : Nat;
9267 Nam : Name_Id) return Node_Id;
9268 -- Returns an attribute reference
9269 -- E'First or E'Last
9270 -- with a source location of Loc.
9272 -- Nam is Name_First or Name_Last, according to which attribute is
9273 -- desired. If Indx is non-zero, it is passed as a literal in the
9274 -- Expressions of the attribute reference (identifying the desired
9275 -- array dimension).
9277 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
9278 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
9279 -- Returns expression to compute:
9280 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
9282 function Range_E_Cond
9283 (Exptyp : Entity_Id;
9284 Typ : Entity_Id;
9285 Indx : Nat)
9286 return Node_Id;
9287 -- Returns expression to compute:
9288 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
9290 function Range_Equal_E_Cond
9291 (Exptyp : Entity_Id;
9292 Typ : Entity_Id;
9293 Indx : Nat) return Node_Id;
9294 -- Returns expression to compute:
9295 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
9297 function Range_N_Cond
9298 (Expr : Node_Id;
9299 Typ : Entity_Id;
9300 Indx : Nat) return Node_Id;
9301 -- Return expression to compute:
9302 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
9304 ---------------
9305 -- Add_Check --
9306 ---------------
9308 procedure Add_Check (N : Node_Id) is
9309 begin
9310 if Present (N) then
9312 -- For now, ignore attempt to place more than 2 checks ???
9314 if Num_Checks = 2 then
9315 return;
9316 end if;
9318 pragma Assert (Num_Checks <= 1);
9319 Num_Checks := Num_Checks + 1;
9320 Ret_Result (Num_Checks) := N;
9321 end if;
9322 end Add_Check;
9324 -------------------------
9325 -- Discrete_Expr_Cond --
9326 -------------------------
9328 function Discrete_Expr_Cond
9329 (Expr : Node_Id;
9330 Typ : Entity_Id) return Node_Id
9332 begin
9333 return
9334 Make_Or_Else (Loc,
9335 Left_Opnd =>
9336 Make_Op_Lt (Loc,
9337 Left_Opnd =>
9338 Convert_To (Base_Type (Typ),
9339 Duplicate_Subexpr_No_Checks (Expr)),
9340 Right_Opnd =>
9341 Convert_To (Base_Type (Typ),
9342 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
9344 Right_Opnd =>
9345 Make_Op_Gt (Loc,
9346 Left_Opnd =>
9347 Convert_To (Base_Type (Typ),
9348 Duplicate_Subexpr_No_Checks (Expr)),
9349 Right_Opnd =>
9350 Convert_To
9351 (Base_Type (Typ),
9352 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
9353 end Discrete_Expr_Cond;
9355 -------------------------
9356 -- Discrete_Range_Cond --
9357 -------------------------
9359 function Discrete_Range_Cond
9360 (Expr : Node_Id;
9361 Typ : Entity_Id) return Node_Id
9363 LB : Node_Id := Low_Bound (Expr);
9364 HB : Node_Id := High_Bound (Expr);
9366 Left_Opnd : Node_Id;
9367 Right_Opnd : Node_Id;
9369 begin
9370 if Nkind (LB) = N_Identifier
9371 and then Ekind (Entity (LB)) = E_Discriminant
9372 then
9373 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
9374 end if;
9376 Left_Opnd :=
9377 Make_Op_Lt (Loc,
9378 Left_Opnd =>
9379 Convert_To
9380 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
9382 Right_Opnd =>
9383 Convert_To
9384 (Base_Type (Typ),
9385 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
9387 if Nkind (HB) = N_Identifier
9388 and then Ekind (Entity (HB)) = E_Discriminant
9389 then
9390 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
9391 end if;
9393 Right_Opnd :=
9394 Make_Op_Gt (Loc,
9395 Left_Opnd =>
9396 Convert_To
9397 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
9399 Right_Opnd =>
9400 Convert_To
9401 (Base_Type (Typ),
9402 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
9404 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
9405 end Discrete_Range_Cond;
9407 -------------------------
9408 -- Get_E_First_Or_Last --
9409 -------------------------
9411 function Get_E_First_Or_Last
9412 (Loc : Source_Ptr;
9413 E : Entity_Id;
9414 Indx : Nat;
9415 Nam : Name_Id) return Node_Id
9417 Exprs : List_Id;
9418 begin
9419 if Indx > 0 then
9420 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
9421 else
9422 Exprs := No_List;
9423 end if;
9425 return Make_Attribute_Reference (Loc,
9426 Prefix => New_Occurrence_Of (E, Loc),
9427 Attribute_Name => Nam,
9428 Expressions => Exprs);
9429 end Get_E_First_Or_Last;
9431 -----------------
9432 -- Get_N_First --
9433 -----------------
9435 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
9436 begin
9437 return
9438 Make_Attribute_Reference (Loc,
9439 Attribute_Name => Name_First,
9440 Prefix =>
9441 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
9442 Expressions => New_List (
9443 Make_Integer_Literal (Loc, Indx)));
9444 end Get_N_First;
9446 ----------------
9447 -- Get_N_Last --
9448 ----------------
9450 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
9451 begin
9452 return
9453 Make_Attribute_Reference (Loc,
9454 Attribute_Name => Name_Last,
9455 Prefix =>
9456 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
9457 Expressions => New_List (
9458 Make_Integer_Literal (Loc, Indx)));
9459 end Get_N_Last;
9461 ------------------
9462 -- Range_E_Cond --
9463 ------------------
9465 function Range_E_Cond
9466 (Exptyp : Entity_Id;
9467 Typ : Entity_Id;
9468 Indx : Nat) return Node_Id
9470 begin
9471 return
9472 Make_Or_Else (Loc,
9473 Left_Opnd =>
9474 Make_Op_Lt (Loc,
9475 Left_Opnd =>
9476 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
9477 Right_Opnd =>
9478 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
9480 Right_Opnd =>
9481 Make_Op_Gt (Loc,
9482 Left_Opnd =>
9483 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
9484 Right_Opnd =>
9485 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
9486 end Range_E_Cond;
9488 ------------------------
9489 -- Range_Equal_E_Cond --
9490 ------------------------
9492 function Range_Equal_E_Cond
9493 (Exptyp : Entity_Id;
9494 Typ : Entity_Id;
9495 Indx : Nat) return Node_Id
9497 begin
9498 return
9499 Make_Or_Else (Loc,
9500 Left_Opnd =>
9501 Make_Op_Ne (Loc,
9502 Left_Opnd =>
9503 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
9504 Right_Opnd =>
9505 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
9507 Right_Opnd =>
9508 Make_Op_Ne (Loc,
9509 Left_Opnd =>
9510 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
9511 Right_Opnd =>
9512 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
9513 end Range_Equal_E_Cond;
9515 ------------------
9516 -- Range_N_Cond --
9517 ------------------
9519 function Range_N_Cond
9520 (Expr : Node_Id;
9521 Typ : Entity_Id;
9522 Indx : Nat) return Node_Id
9524 begin
9525 return
9526 Make_Or_Else (Loc,
9527 Left_Opnd =>
9528 Make_Op_Lt (Loc,
9529 Left_Opnd =>
9530 Get_N_First (Expr, Indx),
9531 Right_Opnd =>
9532 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
9534 Right_Opnd =>
9535 Make_Op_Gt (Loc,
9536 Left_Opnd =>
9537 Get_N_Last (Expr, Indx),
9538 Right_Opnd =>
9539 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
9540 end Range_N_Cond;
9542 -- Start of processing for Selected_Range_Checks
9544 begin
9545 if not Expander_Active then
9546 return Ret_Result;
9547 end if;
9549 if Target_Typ = Any_Type
9550 or else Target_Typ = Any_Composite
9551 or else Raises_Constraint_Error (Ck_Node)
9552 then
9553 return Ret_Result;
9554 end if;
9556 if No (Wnode) then
9557 Wnode := Ck_Node;
9558 end if;
9560 T_Typ := Target_Typ;
9562 if No (Source_Typ) then
9563 S_Typ := Etype (Ck_Node);
9564 else
9565 S_Typ := Source_Typ;
9566 end if;
9568 if S_Typ = Any_Type or else S_Typ = Any_Composite then
9569 return Ret_Result;
9570 end if;
9572 -- The order of evaluating T_Typ before S_Typ seems to be critical
9573 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
9574 -- in, and since Node can be an N_Range node, it might be invalid.
9575 -- Should there be an assert check somewhere for taking the Etype of
9576 -- an N_Range node ???
9578 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
9579 S_Typ := Designated_Type (S_Typ);
9580 T_Typ := Designated_Type (T_Typ);
9581 Do_Access := True;
9583 -- A simple optimization for the null case
9585 if Known_Null (Ck_Node) then
9586 return Ret_Result;
9587 end if;
9588 end if;
9590 -- For an N_Range Node, check for a null range and then if not
9591 -- null generate a range check action.
9593 if Nkind (Ck_Node) = N_Range then
9595 -- There's no point in checking a range against itself
9597 if Ck_Node = Scalar_Range (T_Typ) then
9598 return Ret_Result;
9599 end if;
9601 declare
9602 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
9603 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
9604 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
9605 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
9607 LB : Node_Id := Low_Bound (Ck_Node);
9608 HB : Node_Id := High_Bound (Ck_Node);
9609 Known_LB : Boolean;
9610 Known_HB : Boolean;
9612 Null_Range : Boolean;
9613 Out_Of_Range_L : Boolean;
9614 Out_Of_Range_H : Boolean;
9616 begin
9617 -- Compute what is known at compile time
9619 if Known_T_LB and Known_T_HB then
9620 if Compile_Time_Known_Value (LB) then
9621 Known_LB := True;
9623 -- There's no point in checking that a bound is within its
9624 -- own range so pretend that it is known in this case. First
9625 -- deal with low bound.
9627 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
9628 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
9629 then
9630 LB := T_LB;
9631 Known_LB := True;
9633 else
9634 Known_LB := False;
9635 end if;
9637 -- Likewise for the high bound
9639 if Compile_Time_Known_Value (HB) then
9640 Known_HB := True;
9642 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
9643 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
9644 then
9645 HB := T_HB;
9646 Known_HB := True;
9647 else
9648 Known_HB := False;
9649 end if;
9650 end if;
9652 -- Check for case where everything is static and we can do the
9653 -- check at compile time. This is skipped if we have an access
9654 -- type, since the access value may be null.
9656 -- ??? This code can be improved since you only need to know that
9657 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
9658 -- compile time to emit pertinent messages.
9660 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
9661 and not Do_Access
9662 then
9663 -- Floating-point case
9665 if Is_Floating_Point_Type (S_Typ) then
9666 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
9667 Out_Of_Range_L :=
9668 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
9669 or else
9670 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
9672 Out_Of_Range_H :=
9673 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
9674 or else
9675 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
9677 -- Fixed or discrete type case
9679 else
9680 Null_Range := Expr_Value (HB) < Expr_Value (LB);
9681 Out_Of_Range_L :=
9682 (Expr_Value (LB) < Expr_Value (T_LB))
9683 or else
9684 (Expr_Value (LB) > Expr_Value (T_HB));
9686 Out_Of_Range_H :=
9687 (Expr_Value (HB) > Expr_Value (T_HB))
9688 or else
9689 (Expr_Value (HB) < Expr_Value (T_LB));
9690 end if;
9692 if not Null_Range then
9693 if Out_Of_Range_L then
9694 if No (Warn_Node) then
9695 Add_Check
9696 (Compile_Time_Constraint_Error
9697 (Low_Bound (Ck_Node),
9698 "static value out of range of}??", T_Typ));
9700 else
9701 Add_Check
9702 (Compile_Time_Constraint_Error
9703 (Wnode,
9704 "static range out of bounds of}??", T_Typ));
9705 end if;
9706 end if;
9708 if Out_Of_Range_H then
9709 if No (Warn_Node) then
9710 Add_Check
9711 (Compile_Time_Constraint_Error
9712 (High_Bound (Ck_Node),
9713 "static value out of range of}??", T_Typ));
9715 else
9716 Add_Check
9717 (Compile_Time_Constraint_Error
9718 (Wnode,
9719 "static range out of bounds of}??", T_Typ));
9720 end if;
9721 end if;
9722 end if;
9724 else
9725 declare
9726 LB : Node_Id := Low_Bound (Ck_Node);
9727 HB : Node_Id := High_Bound (Ck_Node);
9729 begin
9730 -- If either bound is a discriminant and we are within the
9731 -- record declaration, it is a use of the discriminant in a
9732 -- constraint of a component, and nothing can be checked
9733 -- here. The check will be emitted within the init proc.
9734 -- Before then, the discriminal has no real meaning.
9735 -- Similarly, if the entity is a discriminal, there is no
9736 -- check to perform yet.
9738 -- The same holds within a discriminated synchronized type,
9739 -- where the discriminant may constrain a component or an
9740 -- entry family.
9742 if Nkind (LB) = N_Identifier
9743 and then Denotes_Discriminant (LB, True)
9744 then
9745 if Current_Scope = Scope (Entity (LB))
9746 or else Is_Concurrent_Type (Current_Scope)
9747 or else Ekind (Entity (LB)) /= E_Discriminant
9748 then
9749 return Ret_Result;
9750 else
9751 LB :=
9752 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
9753 end if;
9754 end if;
9756 if Nkind (HB) = N_Identifier
9757 and then Denotes_Discriminant (HB, True)
9758 then
9759 if Current_Scope = Scope (Entity (HB))
9760 or else Is_Concurrent_Type (Current_Scope)
9761 or else Ekind (Entity (HB)) /= E_Discriminant
9762 then
9763 return Ret_Result;
9764 else
9765 HB :=
9766 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
9767 end if;
9768 end if;
9770 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
9771 Set_Paren_Count (Cond, 1);
9773 Cond :=
9774 Make_And_Then (Loc,
9775 Left_Opnd =>
9776 Make_Op_Ge (Loc,
9777 Left_Opnd =>
9778 Convert_To (Base_Type (Etype (HB)),
9779 Duplicate_Subexpr_No_Checks (HB)),
9780 Right_Opnd =>
9781 Convert_To (Base_Type (Etype (LB)),
9782 Duplicate_Subexpr_No_Checks (LB))),
9783 Right_Opnd => Cond);
9784 end;
9785 end if;
9786 end;
9788 elsif Is_Scalar_Type (S_Typ) then
9790 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
9791 -- except the above simply sets a flag in the node and lets
9792 -- gigi generate the check base on the Etype of the expression.
9793 -- Sometimes, however we want to do a dynamic check against an
9794 -- arbitrary target type, so we do that here.
9796 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
9797 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
9799 -- For literals, we can tell if the constraint error will be
9800 -- raised at compile time, so we never need a dynamic check, but
9801 -- if the exception will be raised, then post the usual warning,
9802 -- and replace the literal with a raise constraint error
9803 -- expression. As usual, skip this for access types
9805 elsif Compile_Time_Known_Value (Ck_Node) and then not Do_Access then
9806 declare
9807 LB : constant Node_Id := Type_Low_Bound (T_Typ);
9808 UB : constant Node_Id := Type_High_Bound (T_Typ);
9810 Out_Of_Range : Boolean;
9811 Static_Bounds : constant Boolean :=
9812 Compile_Time_Known_Value (LB)
9813 and Compile_Time_Known_Value (UB);
9815 begin
9816 -- Following range tests should use Sem_Eval routine ???
9818 if Static_Bounds then
9819 if Is_Floating_Point_Type (S_Typ) then
9820 Out_Of_Range :=
9821 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
9822 or else
9823 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
9825 -- Fixed or discrete type
9827 else
9828 Out_Of_Range :=
9829 Expr_Value (Ck_Node) < Expr_Value (LB)
9830 or else
9831 Expr_Value (Ck_Node) > Expr_Value (UB);
9832 end if;
9834 -- Bounds of the type are static and the literal is out of
9835 -- range so output a warning message.
9837 if Out_Of_Range then
9838 if No (Warn_Node) then
9839 Add_Check
9840 (Compile_Time_Constraint_Error
9841 (Ck_Node,
9842 "static value out of range of}??", T_Typ));
9844 else
9845 Add_Check
9846 (Compile_Time_Constraint_Error
9847 (Wnode,
9848 "static value out of range of}??", T_Typ));
9849 end if;
9850 end if;
9852 else
9853 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
9854 end if;
9855 end;
9857 -- Here for the case of a non-static expression, we need a runtime
9858 -- check unless the source type range is guaranteed to be in the
9859 -- range of the target type.
9861 else
9862 if not In_Subrange_Of (S_Typ, T_Typ) then
9863 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
9864 end if;
9865 end if;
9866 end if;
9868 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
9869 if Is_Constrained (T_Typ) then
9871 Expr_Actual := Get_Referenced_Object (Ck_Node);
9872 Exptyp := Get_Actual_Subtype (Expr_Actual);
9874 if Is_Access_Type (Exptyp) then
9875 Exptyp := Designated_Type (Exptyp);
9876 end if;
9878 -- String_Literal case. This needs to be handled specially be-
9879 -- cause no index types are available for string literals. The
9880 -- condition is simply:
9882 -- T_Typ'Length = string-literal-length
9884 if Nkind (Expr_Actual) = N_String_Literal then
9885 null;
9887 -- General array case. Here we have a usable actual subtype for
9888 -- the expression, and the condition is built from the two types
9890 -- T_Typ'First < Exptyp'First or else
9891 -- T_Typ'Last > Exptyp'Last or else
9892 -- T_Typ'First(1) < Exptyp'First(1) or else
9893 -- T_Typ'Last(1) > Exptyp'Last(1) or else
9894 -- ...
9896 elsif Is_Constrained (Exptyp) then
9897 declare
9898 Ndims : constant Nat := Number_Dimensions (T_Typ);
9900 L_Index : Node_Id;
9901 R_Index : Node_Id;
9903 begin
9904 L_Index := First_Index (T_Typ);
9905 R_Index := First_Index (Exptyp);
9907 for Indx in 1 .. Ndims loop
9908 if not (Nkind (L_Index) = N_Raise_Constraint_Error
9909 or else
9910 Nkind (R_Index) = N_Raise_Constraint_Error)
9911 then
9912 -- Deal with compile time length check. Note that we
9913 -- skip this in the access case, because the access
9914 -- value may be null, so we cannot know statically.
9916 if not
9917 Subtypes_Statically_Match
9918 (Etype (L_Index), Etype (R_Index))
9919 then
9920 -- If the target type is constrained then we
9921 -- have to check for exact equality of bounds
9922 -- (required for qualified expressions).
9924 if Is_Constrained (T_Typ) then
9925 Evolve_Or_Else
9926 (Cond,
9927 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
9928 else
9929 Evolve_Or_Else
9930 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
9931 end if;
9932 end if;
9934 Next (L_Index);
9935 Next (R_Index);
9936 end if;
9937 end loop;
9938 end;
9940 -- Handle cases where we do not get a usable actual subtype that
9941 -- is constrained. This happens for example in the function call
9942 -- and explicit dereference cases. In these cases, we have to get
9943 -- the length or range from the expression itself, making sure we
9944 -- do not evaluate it more than once.
9946 -- Here Ck_Node is the original expression, or more properly the
9947 -- result of applying Duplicate_Expr to the original tree,
9948 -- forcing the result to be a name.
9950 else
9951 declare
9952 Ndims : constant Nat := Number_Dimensions (T_Typ);
9954 begin
9955 -- Build the condition for the explicit dereference case
9957 for Indx in 1 .. Ndims loop
9958 Evolve_Or_Else
9959 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
9960 end loop;
9961 end;
9962 end if;
9964 else
9965 -- For a conversion to an unconstrained array type, generate an
9966 -- Action to check that the bounds of the source value are within
9967 -- the constraints imposed by the target type (RM 4.6(38)). No
9968 -- check is needed for a conversion to an access to unconstrained
9969 -- array type, as 4.6(24.15/2) requires the designated subtypes
9970 -- of the two access types to statically match.
9972 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
9973 and then not Do_Access
9974 then
9975 declare
9976 Opnd_Index : Node_Id;
9977 Targ_Index : Node_Id;
9978 Opnd_Range : Node_Id;
9980 begin
9981 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
9982 Targ_Index := First_Index (T_Typ);
9983 while Present (Opnd_Index) loop
9985 -- If the index is a range, use its bounds. If it is an
9986 -- entity (as will be the case if it is a named subtype
9987 -- or an itype created for a slice) retrieve its range.
9989 if Is_Entity_Name (Opnd_Index)
9990 and then Is_Type (Entity (Opnd_Index))
9991 then
9992 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
9993 else
9994 Opnd_Range := Opnd_Index;
9995 end if;
9997 if Nkind (Opnd_Range) = N_Range then
9998 if Is_In_Range
9999 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10000 Assume_Valid => True)
10001 and then
10002 Is_In_Range
10003 (High_Bound (Opnd_Range), Etype (Targ_Index),
10004 Assume_Valid => True)
10005 then
10006 null;
10008 -- If null range, no check needed
10010 elsif
10011 Compile_Time_Known_Value (High_Bound (Opnd_Range))
10012 and then
10013 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
10014 and then
10015 Expr_Value (High_Bound (Opnd_Range)) <
10016 Expr_Value (Low_Bound (Opnd_Range))
10017 then
10018 null;
10020 elsif Is_Out_Of_Range
10021 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10022 Assume_Valid => True)
10023 or else
10024 Is_Out_Of_Range
10025 (High_Bound (Opnd_Range), Etype (Targ_Index),
10026 Assume_Valid => True)
10027 then
10028 Add_Check
10029 (Compile_Time_Constraint_Error
10030 (Wnode, "value out of range of}??", T_Typ));
10032 else
10033 Evolve_Or_Else
10034 (Cond,
10035 Discrete_Range_Cond
10036 (Opnd_Range, Etype (Targ_Index)));
10037 end if;
10038 end if;
10040 Next_Index (Opnd_Index);
10041 Next_Index (Targ_Index);
10042 end loop;
10043 end;
10044 end if;
10045 end if;
10046 end if;
10048 -- Construct the test and insert into the tree
10050 if Present (Cond) then
10051 if Do_Access then
10052 Cond := Guard_Access (Cond, Loc, Ck_Node);
10053 end if;
10055 Add_Check
10056 (Make_Raise_Constraint_Error (Loc,
10057 Condition => Cond,
10058 Reason => CE_Range_Check_Failed));
10059 end if;
10061 return Ret_Result;
10062 end Selected_Range_Checks;
10064 -------------------------------
10065 -- Storage_Checks_Suppressed --
10066 -------------------------------
10068 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
10069 begin
10070 if Present (E) and then Checks_May_Be_Suppressed (E) then
10071 return Is_Check_Suppressed (E, Storage_Check);
10072 else
10073 return Scope_Suppress.Suppress (Storage_Check);
10074 end if;
10075 end Storage_Checks_Suppressed;
10077 ---------------------------
10078 -- Tag_Checks_Suppressed --
10079 ---------------------------
10081 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
10082 begin
10083 if Present (E)
10084 and then Checks_May_Be_Suppressed (E)
10085 then
10086 return Is_Check_Suppressed (E, Tag_Check);
10087 else
10088 return Scope_Suppress.Suppress (Tag_Check);
10089 end if;
10090 end Tag_Checks_Suppressed;
10092 ---------------------------------------
10093 -- Validate_Alignment_Check_Warnings --
10094 ---------------------------------------
10096 procedure Validate_Alignment_Check_Warnings is
10097 begin
10098 for J in Alignment_Warnings.First .. Alignment_Warnings.Last loop
10099 declare
10100 AWR : Alignment_Warnings_Record
10101 renames Alignment_Warnings.Table (J);
10102 begin
10103 if Known_Alignment (AWR.E)
10104 and then AWR.A mod Alignment (AWR.E) = 0
10105 then
10106 Delete_Warning_And_Continuations (AWR.W);
10107 end if;
10108 end;
10109 end loop;
10110 end Validate_Alignment_Check_Warnings;
10112 --------------------------
10113 -- Validity_Check_Range --
10114 --------------------------
10116 procedure Validity_Check_Range (N : Node_Id) is
10117 begin
10118 if Validity_Checks_On and Validity_Check_Operands then
10119 if Nkind (N) = N_Range then
10120 Ensure_Valid (Low_Bound (N));
10121 Ensure_Valid (High_Bound (N));
10122 end if;
10123 end if;
10124 end Validity_Check_Range;
10126 --------------------------------
10127 -- Validity_Checks_Suppressed --
10128 --------------------------------
10130 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
10131 begin
10132 if Present (E) and then Checks_May_Be_Suppressed (E) then
10133 return Is_Check_Suppressed (E, Validity_Check);
10134 else
10135 return Scope_Suppress.Suppress (Validity_Check);
10136 end if;
10137 end Validity_Checks_Suppressed;
10139 end Checks;