2010-07-27 Paolo Carlini <paolo.carlini@oracle.com>
[official-gcc/alias-decl.git] / gcc / ada / checks.adb
blob59270e875a92fd539a5b476864c646102d314608
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-2010, 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 Debug; use Debug;
28 with Einfo; use Einfo;
29 with Errout; use Errout;
30 with Exp_Ch2; use Exp_Ch2;
31 with Exp_Ch4; use Exp_Ch4;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Pakd; use Exp_Pakd;
34 with Exp_Util; use Exp_Util;
35 with Elists; use Elists;
36 with Eval_Fat; use Eval_Fat;
37 with Freeze; use Freeze;
38 with Lib; use Lib;
39 with Nlists; use Nlists;
40 with Nmake; use Nmake;
41 with Opt; use Opt;
42 with Output; use Output;
43 with Restrict; use Restrict;
44 with Rident; use Rident;
45 with Rtsfind; use Rtsfind;
46 with Sem; use Sem;
47 with Sem_Aux; use Sem_Aux;
48 with Sem_Eval; use Sem_Eval;
49 with Sem_Ch3; use Sem_Ch3;
50 with Sem_Ch8; use Sem_Ch8;
51 with Sem_Res; use Sem_Res;
52 with Sem_Util; use Sem_Util;
53 with Sem_Warn; use Sem_Warn;
54 with Sinfo; use Sinfo;
55 with Sinput; use Sinput;
56 with Snames; use Snames;
57 with Sprint; use Sprint;
58 with Stand; use Stand;
59 with Targparm; use Targparm;
60 with Tbuild; use Tbuild;
61 with Ttypes; use Ttypes;
62 with Urealp; use Urealp;
63 with Validsw; use Validsw;
65 package body Checks is
67 -- General note: many of these routines are concerned with generating
68 -- checking code to make sure that constraint error is raised at runtime.
69 -- Clearly this code is only needed if the expander is active, since
70 -- otherwise we will not be generating code or going into the runtime
71 -- execution anyway.
73 -- We therefore disconnect most of these checks if the expander is
74 -- inactive. This has the additional benefit that we do not need to
75 -- worry about the tree being messed up by previous errors (since errors
76 -- turn off expansion anyway).
78 -- There are a few exceptions to the above rule. For instance routines
79 -- such as Apply_Scalar_Range_Check that do not insert any code can be
80 -- safely called even when the Expander is inactive (but Errors_Detected
81 -- is 0). The benefit of executing this code when expansion is off, is
82 -- the ability to emit constraint error warning for static expressions
83 -- even when we are not generating code.
85 -------------------------------------
86 -- Suppression of Redundant Checks --
87 -------------------------------------
89 -- This unit implements a limited circuit for removal of redundant
90 -- checks. The processing is based on a tracing of simple sequential
91 -- flow. For any sequence of statements, we save expressions that are
92 -- marked to be checked, and then if the same expression appears later
93 -- with the same check, then under certain circumstances, the second
94 -- check can be suppressed.
96 -- Basically, we can suppress the check if we know for certain that
97 -- the previous expression has been elaborated (together with its
98 -- check), and we know that the exception frame is the same, and that
99 -- nothing has happened to change the result of the exception.
101 -- Let us examine each of these three conditions in turn to describe
102 -- how we ensure that this condition is met.
104 -- First, we need to know for certain that the previous expression has
105 -- been executed. This is done principly by the mechanism of calling
106 -- Conditional_Statements_Begin at the start of any statement sequence
107 -- and Conditional_Statements_End at the end. The End call causes all
108 -- checks remembered since the Begin call to be discarded. This does
109 -- miss a few cases, notably the case of a nested BEGIN-END block with
110 -- no exception handlers. But the important thing is to be conservative.
111 -- The other protection is that all checks are discarded if a label
112 -- is encountered, since then the assumption of sequential execution
113 -- is violated, and we don't know enough about the flow.
115 -- Second, we need to know that the exception frame is the same. We
116 -- do this by killing all remembered checks when we enter a new frame.
117 -- Again, that's over-conservative, but generally the cases we can help
118 -- with are pretty local anyway (like the body of a loop for example).
120 -- Third, we must be sure to forget any checks which are no longer valid.
121 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
122 -- used to note any changes to local variables. We only attempt to deal
123 -- with checks involving local variables, so we do not need to worry
124 -- about global variables. Second, a call to any non-global procedure
125 -- causes us to abandon all stored checks, since such a all may affect
126 -- the values of any local variables.
128 -- The following define the data structures used to deal with remembering
129 -- checks so that redundant checks can be eliminated as described above.
131 -- Right now, the only expressions that we deal with are of the form of
132 -- simple local objects (either declared locally, or IN parameters) or
133 -- such objects plus/minus a compile time known constant. We can do
134 -- more later on if it seems worthwhile, but this catches many simple
135 -- cases in practice.
137 -- The following record type reflects a single saved check. An entry
138 -- is made in the stack of saved checks if and only if the expression
139 -- has been elaborated with the indicated checks.
141 type Saved_Check is record
142 Killed : Boolean;
143 -- Set True if entry is killed by Kill_Checks
145 Entity : Entity_Id;
146 -- The entity involved in the expression that is checked
148 Offset : Uint;
149 -- A compile time value indicating the result of adding or
150 -- subtracting a compile time value. This value is to be
151 -- added to the value of the Entity. A value of zero is
152 -- used for the case of a simple entity reference.
154 Check_Type : Character;
155 -- This is set to 'R' for a range check (in which case Target_Type
156 -- is set to the target type for the range check) or to 'O' for an
157 -- overflow check (in which case Target_Type is set to Empty).
159 Target_Type : Entity_Id;
160 -- Used only if Do_Range_Check is set. Records the target type for
161 -- the check. We need this, because a check is a duplicate only if
162 -- it has a the same target type (or more accurately one with a
163 -- range that is smaller or equal to the stored target type of a
164 -- saved check).
165 end record;
167 -- The following table keeps track of saved checks. Rather than use an
168 -- extensible table. We just use a table of fixed size, and we discard
169 -- any saved checks that do not fit. That's very unlikely to happen and
170 -- this is only an optimization in any case.
172 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
173 -- Array of saved checks
175 Num_Saved_Checks : Nat := 0;
176 -- Number of saved checks
178 -- The following stack keeps track of statement ranges. It is treated
179 -- as a stack. When Conditional_Statements_Begin is called, an entry
180 -- is pushed onto this stack containing the value of Num_Saved_Checks
181 -- at the time of the call. Then when Conditional_Statements_End is
182 -- called, this value is popped off and used to reset Num_Saved_Checks.
184 -- Note: again, this is a fixed length stack with a size that should
185 -- always be fine. If the value of the stack pointer goes above the
186 -- limit, then we just forget all saved checks.
188 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
189 Saved_Checks_TOS : Nat := 0;
191 -----------------------
192 -- Local Subprograms --
193 -----------------------
195 procedure Apply_Float_Conversion_Check
196 (Ck_Node : Node_Id;
197 Target_Typ : Entity_Id);
198 -- The checks on a conversion from a floating-point type to an integer
199 -- type are delicate. They have to be performed before conversion, they
200 -- have to raise an exception when the operand is a NaN, and rounding must
201 -- be taken into account to determine the safe bounds of the operand.
203 procedure Apply_Selected_Length_Checks
204 (Ck_Node : Node_Id;
205 Target_Typ : Entity_Id;
206 Source_Typ : Entity_Id;
207 Do_Static : Boolean);
208 -- This is the subprogram that does all the work for Apply_Length_Check
209 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
210 -- described for the above routines. The Do_Static flag indicates that
211 -- only a static check is to be done.
213 procedure Apply_Selected_Range_Checks
214 (Ck_Node : Node_Id;
215 Target_Typ : Entity_Id;
216 Source_Typ : Entity_Id;
217 Do_Static : Boolean);
218 -- This is the subprogram that does all the work for Apply_Range_Check.
219 -- Expr, Target_Typ and Source_Typ are as described for the above
220 -- routine. The Do_Static flag indicates that only a static check is
221 -- to be done.
223 type Check_Type is new Check_Id range Access_Check .. Division_Check;
224 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
225 -- This function is used to see if an access or division by zero check is
226 -- needed. The check is to be applied to a single variable appearing in the
227 -- source, and N is the node for the reference. If N is not of this form,
228 -- True is returned with no further processing. If N is of the right form,
229 -- then further processing determines if the given Check is needed.
231 -- The particular circuit is to see if we have the case of a check that is
232 -- not needed because it appears in the right operand of a short circuited
233 -- conditional where the left operand guards the check. For example:
235 -- if Var = 0 or else Q / Var > 12 then
236 -- ...
237 -- end if;
239 -- In this example, the division check is not required. At the same time
240 -- we can issue warnings for suspicious use of non-short-circuited forms,
241 -- such as:
243 -- if Var = 0 or Q / Var > 12 then
244 -- ...
245 -- end if;
247 procedure Find_Check
248 (Expr : Node_Id;
249 Check_Type : Character;
250 Target_Type : Entity_Id;
251 Entry_OK : out Boolean;
252 Check_Num : out Nat;
253 Ent : out Entity_Id;
254 Ofs : out Uint);
255 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
256 -- to see if a check is of the form for optimization, and if so, to see
257 -- if it has already been performed. Expr is the expression to check,
258 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
259 -- Target_Type is the target type for a range check, and Empty for an
260 -- overflow check. If the entry is not of the form for optimization,
261 -- then Entry_OK is set to False, and the remaining out parameters
262 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
263 -- entity and offset from the expression. Check_Num is the number of
264 -- a matching saved entry in Saved_Checks, or zero if no such entry
265 -- is located.
267 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
268 -- If a discriminal is used in constraining a prival, Return reference
269 -- to the discriminal of the protected body (which renames the parameter
270 -- of the enclosing protected operation). This clumsy transformation is
271 -- needed because privals are created too late and their actual subtypes
272 -- are not available when analysing the bodies of the protected operations.
273 -- This function is called whenever the bound is an entity and the scope
274 -- indicates a protected operation. If the bound is an in-parameter of
275 -- a protected operation that is not a prival, the function returns the
276 -- bound itself.
277 -- To be cleaned up???
279 function Guard_Access
280 (Cond : Node_Id;
281 Loc : Source_Ptr;
282 Ck_Node : Node_Id) return Node_Id;
283 -- In the access type case, guard the test with a test to ensure
284 -- that the access value is non-null, since the checks do not
285 -- not apply to null access values.
287 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
288 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
289 -- Constraint_Error node.
291 function Range_Or_Validity_Checks_Suppressed
292 (Expr : Node_Id) return Boolean;
293 -- Returns True if either range or validity checks or both are suppressed
294 -- for the type of the given expression, or, if the expression is the name
295 -- of an entity, if these checks are suppressed for the entity.
297 function Selected_Length_Checks
298 (Ck_Node : Node_Id;
299 Target_Typ : Entity_Id;
300 Source_Typ : Entity_Id;
301 Warn_Node : Node_Id) return Check_Result;
302 -- Like Apply_Selected_Length_Checks, except it doesn't modify
303 -- anything, just returns a list of nodes as described in the spec of
304 -- this package for the Range_Check function.
306 function Selected_Range_Checks
307 (Ck_Node : Node_Id;
308 Target_Typ : Entity_Id;
309 Source_Typ : Entity_Id;
310 Warn_Node : Node_Id) return Check_Result;
311 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
312 -- just returns a list of nodes as described in the spec of this package
313 -- for the Range_Check function.
315 ------------------------------
316 -- Access_Checks_Suppressed --
317 ------------------------------
319 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
320 begin
321 if Present (E) and then Checks_May_Be_Suppressed (E) then
322 return Is_Check_Suppressed (E, Access_Check);
323 else
324 return Scope_Suppress (Access_Check);
325 end if;
326 end Access_Checks_Suppressed;
328 -------------------------------------
329 -- Accessibility_Checks_Suppressed --
330 -------------------------------------
332 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
333 begin
334 if Present (E) and then Checks_May_Be_Suppressed (E) then
335 return Is_Check_Suppressed (E, Accessibility_Check);
336 else
337 return Scope_Suppress (Accessibility_Check);
338 end if;
339 end Accessibility_Checks_Suppressed;
341 -----------------------------
342 -- Activate_Division_Check --
343 -----------------------------
345 procedure Activate_Division_Check (N : Node_Id) is
346 begin
347 Set_Do_Division_Check (N, True);
348 Possible_Local_Raise (N, Standard_Constraint_Error);
349 end Activate_Division_Check;
351 -----------------------------
352 -- Activate_Overflow_Check --
353 -----------------------------
355 procedure Activate_Overflow_Check (N : Node_Id) is
356 begin
357 Set_Do_Overflow_Check (N, True);
358 Possible_Local_Raise (N, Standard_Constraint_Error);
359 end Activate_Overflow_Check;
361 --------------------------
362 -- Activate_Range_Check --
363 --------------------------
365 procedure Activate_Range_Check (N : Node_Id) is
366 begin
367 Set_Do_Range_Check (N, True);
368 Possible_Local_Raise (N, Standard_Constraint_Error);
369 end Activate_Range_Check;
371 ---------------------------------
372 -- Alignment_Checks_Suppressed --
373 ---------------------------------
375 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
376 begin
377 if Present (E) and then Checks_May_Be_Suppressed (E) then
378 return Is_Check_Suppressed (E, Alignment_Check);
379 else
380 return Scope_Suppress (Alignment_Check);
381 end if;
382 end Alignment_Checks_Suppressed;
384 -------------------------
385 -- Append_Range_Checks --
386 -------------------------
388 procedure Append_Range_Checks
389 (Checks : Check_Result;
390 Stmts : List_Id;
391 Suppress_Typ : Entity_Id;
392 Static_Sloc : Source_Ptr;
393 Flag_Node : Node_Id)
395 Internal_Flag_Node : constant Node_Id := Flag_Node;
396 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
398 Checks_On : constant Boolean :=
399 (not Index_Checks_Suppressed (Suppress_Typ))
400 or else
401 (not Range_Checks_Suppressed (Suppress_Typ));
403 begin
404 -- For now we just return if Checks_On is false, however this should
405 -- be enhanced to check for an always True value in the condition
406 -- and to generate a compilation warning???
408 if not Checks_On then
409 return;
410 end if;
412 for J in 1 .. 2 loop
413 exit when No (Checks (J));
415 if Nkind (Checks (J)) = N_Raise_Constraint_Error
416 and then Present (Condition (Checks (J)))
417 then
418 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
419 Append_To (Stmts, Checks (J));
420 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
421 end if;
423 else
424 Append_To
425 (Stmts,
426 Make_Raise_Constraint_Error (Internal_Static_Sloc,
427 Reason => CE_Range_Check_Failed));
428 end if;
429 end loop;
430 end Append_Range_Checks;
432 ------------------------
433 -- Apply_Access_Check --
434 ------------------------
436 procedure Apply_Access_Check (N : Node_Id) is
437 P : constant Node_Id := Prefix (N);
439 begin
440 -- We do not need checks if we are not generating code (i.e. the
441 -- expander is not active). This is not just an optimization, there
442 -- are cases (e.g. with pragma Debug) where generating the checks
443 -- can cause real trouble).
445 if not Expander_Active then
446 return;
447 end if;
449 -- No check if short circuiting makes check unnecessary
451 if not Check_Needed (P, Access_Check) then
452 return;
453 end if;
455 -- No check if accessing the Offset_To_Top component of a dispatch
456 -- table. They are safe by construction.
458 if Tagged_Type_Expansion
459 and then Present (Etype (P))
460 and then RTU_Loaded (Ada_Tags)
461 and then RTE_Available (RE_Offset_To_Top_Ptr)
462 and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
463 then
464 return;
465 end if;
467 -- Otherwise go ahead and install the check
469 Install_Null_Excluding_Check (P);
470 end Apply_Access_Check;
472 -------------------------------
473 -- Apply_Accessibility_Check --
474 -------------------------------
476 procedure Apply_Accessibility_Check
477 (N : Node_Id;
478 Typ : Entity_Id;
479 Insert_Node : Node_Id)
481 Loc : constant Source_Ptr := Sloc (N);
482 Param_Ent : constant Entity_Id := Param_Entity (N);
483 Param_Level : Node_Id;
484 Type_Level : Node_Id;
486 begin
487 if Inside_A_Generic then
488 return;
490 -- Only apply the run-time check if the access parameter has an
491 -- associated extra access level parameter and when the level of the
492 -- type is less deep than the level of the access parameter, and
493 -- accessibility checks are not suppressed.
495 elsif Present (Param_Ent)
496 and then Present (Extra_Accessibility (Param_Ent))
497 and then UI_Gt (Object_Access_Level (N), Type_Access_Level (Typ))
498 and then not Accessibility_Checks_Suppressed (Param_Ent)
499 and then not Accessibility_Checks_Suppressed (Typ)
500 then
501 Param_Level :=
502 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
504 Type_Level :=
505 Make_Integer_Literal (Loc, Type_Access_Level (Typ));
507 -- Raise Program_Error if the accessibility level of the access
508 -- parameter is deeper than the level of the target access type.
510 Insert_Action (Insert_Node,
511 Make_Raise_Program_Error (Loc,
512 Condition =>
513 Make_Op_Gt (Loc,
514 Left_Opnd => Param_Level,
515 Right_Opnd => Type_Level),
516 Reason => PE_Accessibility_Check_Failed));
518 Analyze_And_Resolve (N);
519 end if;
520 end Apply_Accessibility_Check;
522 --------------------------------
523 -- Apply_Address_Clause_Check --
524 --------------------------------
526 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
527 AC : constant Node_Id := Address_Clause (E);
528 Loc : constant Source_Ptr := Sloc (AC);
529 Typ : constant Entity_Id := Etype (E);
530 Aexp : constant Node_Id := Expression (AC);
532 Expr : Node_Id;
533 -- Address expression (not necessarily the same as Aexp, for example
534 -- when Aexp is a reference to a constant, in which case Expr gets
535 -- reset to reference the value expression of the constant.
537 procedure Compile_Time_Bad_Alignment;
538 -- Post error warnings when alignment is known to be incompatible. Note
539 -- that we do not go as far as inserting a raise of Program_Error since
540 -- this is an erroneous case, and it may happen that we are lucky and an
541 -- underaligned address turns out to be OK after all.
543 --------------------------------
544 -- Compile_Time_Bad_Alignment --
545 --------------------------------
547 procedure Compile_Time_Bad_Alignment is
548 begin
549 if Address_Clause_Overlay_Warnings then
550 Error_Msg_FE
551 ("?specified address for& may be inconsistent with alignment ",
552 Aexp, E);
553 Error_Msg_FE
554 ("\?program execution may be erroneous (RM 13.3(27))",
555 Aexp, E);
556 Set_Address_Warning_Posted (AC);
557 end if;
558 end Compile_Time_Bad_Alignment;
560 -- Start of processing for Apply_Address_Clause_Check
562 begin
563 -- See if alignment check needed. Note that we never need a check if the
564 -- maximum alignment is one, since the check will always succeed.
566 -- Note: we do not check for checks suppressed here, since that check
567 -- was done in Sem_Ch13 when the address clause was processed. We are
568 -- only called if checks were not suppressed. The reason for this is
569 -- that we have to delay the call to Apply_Alignment_Check till freeze
570 -- time (so that all types etc are elaborated), but we have to check
571 -- the status of check suppressing at the point of the address clause.
573 if No (AC)
574 or else not Check_Address_Alignment (AC)
575 or else Maximum_Alignment = 1
576 then
577 return;
578 end if;
580 -- Obtain expression from address clause
582 Expr := Expression (AC);
584 -- The following loop digs for the real expression to use in the check
586 loop
587 -- For constant, get constant expression
589 if Is_Entity_Name (Expr)
590 and then Ekind (Entity (Expr)) = E_Constant
591 then
592 Expr := Constant_Value (Entity (Expr));
594 -- For unchecked conversion, get result to convert
596 elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
597 Expr := Expression (Expr);
599 -- For (common case) of To_Address call, get argument
601 elsif Nkind (Expr) = N_Function_Call
602 and then Is_Entity_Name (Name (Expr))
603 and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
604 then
605 Expr := First (Parameter_Associations (Expr));
607 if Nkind (Expr) = N_Parameter_Association then
608 Expr := Explicit_Actual_Parameter (Expr);
609 end if;
611 -- We finally have the real expression
613 else
614 exit;
615 end if;
616 end loop;
618 -- See if we know that Expr has a bad alignment at compile time
620 if Compile_Time_Known_Value (Expr)
621 and then (Known_Alignment (E) or else Known_Alignment (Typ))
622 then
623 declare
624 AL : Uint := Alignment (Typ);
626 begin
627 -- The object alignment might be more restrictive than the
628 -- type alignment.
630 if Known_Alignment (E) then
631 AL := Alignment (E);
632 end if;
634 if Expr_Value (Expr) mod AL /= 0 then
635 Compile_Time_Bad_Alignment;
636 else
637 return;
638 end if;
639 end;
641 -- If the expression has the form X'Address, then we can find out if
642 -- the object X has an alignment that is compatible with the object E.
643 -- If it hasn't or we don't know, we defer issuing the warning until
644 -- the end of the compilation to take into account back end annotations.
646 elsif Nkind (Expr) = N_Attribute_Reference
647 and then Attribute_Name (Expr) = Name_Address
648 and then Has_Compatible_Alignment (E, Prefix (Expr)) = Known_Compatible
649 then
650 return;
651 end if;
653 -- Here we do not know if the value is acceptable. Stricly we don't have
654 -- to do anything, since if the alignment is bad, we have an erroneous
655 -- program. However we are allowed to check for erroneous conditions and
656 -- we decide to do this by default if the check is not suppressed.
658 -- However, don't do the check if elaboration code is unwanted
660 if Restriction_Active (No_Elaboration_Code) then
661 return;
663 -- Generate a check to raise PE if alignment may be inappropriate
665 else
666 -- If the original expression is a non-static constant, use the
667 -- name of the constant itself rather than duplicating its
668 -- defining expression, which was extracted above.
670 -- Note: Expr is empty if the address-clause is applied to in-mode
671 -- actuals (allowed by 13.1(22)).
673 if not Present (Expr)
674 or else
675 (Is_Entity_Name (Expression (AC))
676 and then Ekind (Entity (Expression (AC))) = E_Constant
677 and then Nkind (Parent (Entity (Expression (AC))))
678 = N_Object_Declaration)
679 then
680 Expr := New_Copy_Tree (Expression (AC));
681 else
682 Remove_Side_Effects (Expr);
683 end if;
685 Insert_After_And_Analyze (N,
686 Make_Raise_Program_Error (Loc,
687 Condition =>
688 Make_Op_Ne (Loc,
689 Left_Opnd =>
690 Make_Op_Mod (Loc,
691 Left_Opnd =>
692 Unchecked_Convert_To
693 (RTE (RE_Integer_Address), Expr),
694 Right_Opnd =>
695 Make_Attribute_Reference (Loc,
696 Prefix => New_Occurrence_Of (E, Loc),
697 Attribute_Name => Name_Alignment)),
698 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
699 Reason => PE_Misaligned_Address_Value),
700 Suppress => All_Checks);
701 return;
702 end if;
704 exception
705 -- If we have some missing run time component in configurable run time
706 -- mode then just skip the check (it is not required in any case).
708 when RE_Not_Available =>
709 return;
710 end Apply_Address_Clause_Check;
712 -------------------------------------
713 -- Apply_Arithmetic_Overflow_Check --
714 -------------------------------------
716 -- This routine is called only if the type is an integer type, and a
717 -- software arithmetic overflow check may be needed for op (add, subtract,
718 -- or multiply). This check is performed only if Software_Overflow_Checking
719 -- is enabled and Do_Overflow_Check is set. In this case we expand the
720 -- operation into a more complex sequence of tests that ensures that
721 -- overflow is properly caught.
723 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
724 Loc : constant Source_Ptr := Sloc (N);
725 Typ : Entity_Id := Etype (N);
726 Rtyp : Entity_Id := Root_Type (Typ);
728 begin
729 -- An interesting special case. If the arithmetic operation appears as
730 -- the operand of a type conversion:
732 -- type1 (x op y)
734 -- and all the following conditions apply:
736 -- arithmetic operation is for a signed integer type
737 -- target type type1 is a static integer subtype
738 -- range of x and y are both included in the range of type1
739 -- range of x op y is included in the range of type1
740 -- size of type1 is at least twice the result size of op
742 -- then we don't do an overflow check in any case, instead we transform
743 -- the operation so that we end up with:
745 -- type1 (type1 (x) op type1 (y))
747 -- This avoids intermediate overflow before the conversion. It is
748 -- explicitly permitted by RM 3.5.4(24):
750 -- For the execution of a predefined operation of a signed integer
751 -- type, the implementation need not raise Constraint_Error if the
752 -- result is outside the base range of the type, so long as the
753 -- correct result is produced.
755 -- It's hard to imagine that any programmer counts on the exception
756 -- being raised in this case, and in any case it's wrong coding to
757 -- have this expectation, given the RM permission. Furthermore, other
758 -- Ada compilers do allow such out of range results.
760 -- Note that we do this transformation even if overflow checking is
761 -- off, since this is precisely about giving the "right" result and
762 -- avoiding the need for an overflow check.
764 -- Note: this circuit is partially redundant with respect to the similar
765 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
766 -- with cases that do not come through here. We still need the following
767 -- processing even with the Exp_Ch4 code in place, since we want to be
768 -- sure not to generate the arithmetic overflow check in these cases
769 -- (Exp_Ch4 would have a hard time removing them once generated).
771 if Is_Signed_Integer_Type (Typ)
772 and then Nkind (Parent (N)) = N_Type_Conversion
773 then
774 declare
775 Target_Type : constant Entity_Id :=
776 Base_Type (Entity (Subtype_Mark (Parent (N))));
778 Llo, Lhi : Uint;
779 Rlo, Rhi : Uint;
780 LOK, ROK : Boolean;
782 Vlo : Uint;
783 Vhi : Uint;
784 VOK : Boolean;
786 Tlo : Uint;
787 Thi : Uint;
789 begin
790 if Is_Integer_Type (Target_Type)
791 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
792 then
793 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
794 Thi := Expr_Value (Type_High_Bound (Target_Type));
796 Determine_Range
797 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
798 Determine_Range
799 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
801 if (LOK and ROK)
802 and then Tlo <= Llo and then Lhi <= Thi
803 and then Tlo <= Rlo and then Rhi <= Thi
804 then
805 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
807 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
808 Rewrite (Left_Opnd (N),
809 Make_Type_Conversion (Loc,
810 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
811 Expression => Relocate_Node (Left_Opnd (N))));
813 Rewrite (Right_Opnd (N),
814 Make_Type_Conversion (Loc,
815 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
816 Expression => Relocate_Node (Right_Opnd (N))));
818 Set_Etype (N, Target_Type);
819 Typ := Target_Type;
820 Rtyp := Root_Type (Typ);
821 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
822 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
824 -- Given that the target type is twice the size of the
825 -- source type, overflow is now impossible, so we can
826 -- safely kill the overflow check and return.
828 Set_Do_Overflow_Check (N, False);
829 return;
830 end if;
831 end if;
832 end if;
833 end;
834 end if;
836 -- Now see if an overflow check is required
838 declare
839 Siz : constant Int := UI_To_Int (Esize (Rtyp));
840 Dsiz : constant Int := Siz * 2;
841 Opnod : Node_Id;
842 Ctyp : Entity_Id;
843 Opnd : Node_Id;
844 Cent : RE_Id;
846 begin
847 -- Skip check if back end does overflow checks, or the overflow flag
848 -- is not set anyway, or we are not doing code expansion, or the
849 -- parent node is a type conversion whose operand is an arithmetic
850 -- operation on signed integers on which the expander can promote
851 -- later the operands to type Integer (see Expand_N_Type_Conversion).
853 -- Special case CLI target, where arithmetic overflow checks can be
854 -- performed for integer and long_integer
856 if Backend_Overflow_Checks_On_Target
857 or else not Do_Overflow_Check (N)
858 or else not Expander_Active
859 or else (Present (Parent (N))
860 and then Nkind (Parent (N)) = N_Type_Conversion
861 and then Integer_Promotion_Possible (Parent (N)))
862 or else
863 (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
864 then
865 return;
866 end if;
868 -- Otherwise, generate the full general code for front end overflow
869 -- detection, which works by doing arithmetic in a larger type:
871 -- x op y
873 -- is expanded into
875 -- Typ (Checktyp (x) op Checktyp (y));
877 -- where Typ is the type of the original expression, and Checktyp is
878 -- an integer type of sufficient length to hold the largest possible
879 -- result.
881 -- If the size of check type exceeds the size of Long_Long_Integer,
882 -- we use a different approach, expanding to:
884 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
886 -- where xxx is Add, Multiply or Subtract as appropriate
888 -- Find check type if one exists
890 if Dsiz <= Standard_Integer_Size then
891 Ctyp := Standard_Integer;
893 elsif Dsiz <= Standard_Long_Long_Integer_Size then
894 Ctyp := Standard_Long_Long_Integer;
896 -- No check type exists, use runtime call
898 else
899 if Nkind (N) = N_Op_Add then
900 Cent := RE_Add_With_Ovflo_Check;
902 elsif Nkind (N) = N_Op_Multiply then
903 Cent := RE_Multiply_With_Ovflo_Check;
905 else
906 pragma Assert (Nkind (N) = N_Op_Subtract);
907 Cent := RE_Subtract_With_Ovflo_Check;
908 end if;
910 Rewrite (N,
911 OK_Convert_To (Typ,
912 Make_Function_Call (Loc,
913 Name => New_Reference_To (RTE (Cent), Loc),
914 Parameter_Associations => New_List (
915 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
916 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
918 Analyze_And_Resolve (N, Typ);
919 return;
920 end if;
922 -- If we fall through, we have the case where we do the arithmetic
923 -- in the next higher type and get the check by conversion. In these
924 -- cases Ctyp is set to the type to be used as the check type.
926 Opnod := Relocate_Node (N);
928 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
930 Analyze (Opnd);
931 Set_Etype (Opnd, Ctyp);
932 Set_Analyzed (Opnd, True);
933 Set_Left_Opnd (Opnod, Opnd);
935 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
937 Analyze (Opnd);
938 Set_Etype (Opnd, Ctyp);
939 Set_Analyzed (Opnd, True);
940 Set_Right_Opnd (Opnod, Opnd);
942 -- The type of the operation changes to the base type of the check
943 -- type, and we reset the overflow check indication, since clearly no
944 -- overflow is possible now that we are using a double length type.
945 -- We also set the Analyzed flag to avoid a recursive attempt to
946 -- expand the node.
948 Set_Etype (Opnod, Base_Type (Ctyp));
949 Set_Do_Overflow_Check (Opnod, False);
950 Set_Analyzed (Opnod, True);
952 -- Now build the outer conversion
954 Opnd := OK_Convert_To (Typ, Opnod);
955 Analyze (Opnd);
956 Set_Etype (Opnd, Typ);
958 -- In the discrete type case, we directly generate the range check
959 -- for the outer operand. This range check will implement the
960 -- required overflow check.
962 if Is_Discrete_Type (Typ) then
963 Rewrite (N, Opnd);
964 Generate_Range_Check
965 (Expression (N), Typ, CE_Overflow_Check_Failed);
967 -- For other types, we enable overflow checking on the conversion,
968 -- after setting the node as analyzed to prevent recursive attempts
969 -- to expand the conversion node.
971 else
972 Set_Analyzed (Opnd, True);
973 Enable_Overflow_Check (Opnd);
974 Rewrite (N, Opnd);
975 end if;
977 exception
978 when RE_Not_Available =>
979 return;
980 end;
981 end Apply_Arithmetic_Overflow_Check;
983 ----------------------------
984 -- Apply_Constraint_Check --
985 ----------------------------
987 procedure Apply_Constraint_Check
988 (N : Node_Id;
989 Typ : Entity_Id;
990 No_Sliding : Boolean := False)
992 Desig_Typ : Entity_Id;
994 begin
995 if Inside_A_Generic then
996 return;
998 elsif Is_Scalar_Type (Typ) then
999 Apply_Scalar_Range_Check (N, Typ);
1001 elsif Is_Array_Type (Typ) then
1003 -- A useful optimization: an aggregate with only an others clause
1004 -- always has the right bounds.
1006 if Nkind (N) = N_Aggregate
1007 and then No (Expressions (N))
1008 and then Nkind
1009 (First (Choices (First (Component_Associations (N)))))
1010 = N_Others_Choice
1011 then
1012 return;
1013 end if;
1015 if Is_Constrained (Typ) then
1016 Apply_Length_Check (N, Typ);
1018 if No_Sliding then
1019 Apply_Range_Check (N, Typ);
1020 end if;
1021 else
1022 Apply_Range_Check (N, Typ);
1023 end if;
1025 elsif (Is_Record_Type (Typ)
1026 or else Is_Private_Type (Typ))
1027 and then Has_Discriminants (Base_Type (Typ))
1028 and then Is_Constrained (Typ)
1029 then
1030 Apply_Discriminant_Check (N, Typ);
1032 elsif Is_Access_Type (Typ) then
1034 Desig_Typ := Designated_Type (Typ);
1036 -- No checks necessary if expression statically null
1038 if Known_Null (N) then
1039 if Can_Never_Be_Null (Typ) then
1040 Install_Null_Excluding_Check (N);
1041 end if;
1043 -- No sliding possible on access to arrays
1045 elsif Is_Array_Type (Desig_Typ) then
1046 if Is_Constrained (Desig_Typ) then
1047 Apply_Length_Check (N, Typ);
1048 end if;
1050 Apply_Range_Check (N, Typ);
1052 elsif Has_Discriminants (Base_Type (Desig_Typ))
1053 and then Is_Constrained (Desig_Typ)
1054 then
1055 Apply_Discriminant_Check (N, Typ);
1056 end if;
1058 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1059 -- this check if the constraint node is illegal, as shown by having
1060 -- an error posted. This additional guard prevents cascaded errors
1061 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1063 if Can_Never_Be_Null (Typ)
1064 and then not Can_Never_Be_Null (Etype (N))
1065 and then not Error_Posted (N)
1066 then
1067 Install_Null_Excluding_Check (N);
1068 end if;
1069 end if;
1070 end Apply_Constraint_Check;
1072 ------------------------------
1073 -- Apply_Discriminant_Check --
1074 ------------------------------
1076 procedure Apply_Discriminant_Check
1077 (N : Node_Id;
1078 Typ : Entity_Id;
1079 Lhs : Node_Id := Empty)
1081 Loc : constant Source_Ptr := Sloc (N);
1082 Do_Access : constant Boolean := Is_Access_Type (Typ);
1083 S_Typ : Entity_Id := Etype (N);
1084 Cond : Node_Id;
1085 T_Typ : Entity_Id;
1087 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1088 -- A heap object with an indefinite subtype is constrained by its
1089 -- initial value, and assigning to it requires a constraint_check.
1090 -- The target may be an explicit dereference, or a renaming of one.
1092 function Is_Aliased_Unconstrained_Component return Boolean;
1093 -- It is possible for an aliased component to have a nominal
1094 -- unconstrained subtype (through instantiation). If this is a
1095 -- discriminated component assigned in the expansion of an aggregate
1096 -- in an initialization, the check must be suppressed. This unusual
1097 -- situation requires a predicate of its own.
1099 ----------------------------------
1100 -- Denotes_Explicit_Dereference --
1101 ----------------------------------
1103 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1104 begin
1105 return
1106 Nkind (Obj) = N_Explicit_Dereference
1107 or else
1108 (Is_Entity_Name (Obj)
1109 and then Present (Renamed_Object (Entity (Obj)))
1110 and then Nkind (Renamed_Object (Entity (Obj))) =
1111 N_Explicit_Dereference);
1112 end Denotes_Explicit_Dereference;
1114 ----------------------------------------
1115 -- Is_Aliased_Unconstrained_Component --
1116 ----------------------------------------
1118 function Is_Aliased_Unconstrained_Component return Boolean is
1119 Comp : Entity_Id;
1120 Pref : Node_Id;
1122 begin
1123 if Nkind (Lhs) /= N_Selected_Component then
1124 return False;
1125 else
1126 Comp := Entity (Selector_Name (Lhs));
1127 Pref := Prefix (Lhs);
1128 end if;
1130 if Ekind (Comp) /= E_Component
1131 or else not Is_Aliased (Comp)
1132 then
1133 return False;
1134 end if;
1136 return not Comes_From_Source (Pref)
1137 and then In_Instance
1138 and then not Is_Constrained (Etype (Comp));
1139 end Is_Aliased_Unconstrained_Component;
1141 -- Start of processing for Apply_Discriminant_Check
1143 begin
1144 if Do_Access then
1145 T_Typ := Designated_Type (Typ);
1146 else
1147 T_Typ := Typ;
1148 end if;
1150 -- Nothing to do if discriminant checks are suppressed or else no code
1151 -- is to be generated
1153 if not Expander_Active
1154 or else Discriminant_Checks_Suppressed (T_Typ)
1155 then
1156 return;
1157 end if;
1159 -- No discriminant checks necessary for an access when expression is
1160 -- statically Null. This is not only an optimization, it is fundamental
1161 -- because otherwise discriminant checks may be generated in init procs
1162 -- for types containing an access to a not-yet-frozen record, causing a
1163 -- deadly forward reference.
1165 -- Also, if the expression is of an access type whose designated type is
1166 -- incomplete, then the access value must be null and we suppress the
1167 -- check.
1169 if Known_Null (N) then
1170 return;
1172 elsif Is_Access_Type (S_Typ) then
1173 S_Typ := Designated_Type (S_Typ);
1175 if Ekind (S_Typ) = E_Incomplete_Type then
1176 return;
1177 end if;
1178 end if;
1180 -- If an assignment target is present, then we need to generate the
1181 -- actual subtype if the target is a parameter or aliased object with
1182 -- an unconstrained nominal subtype.
1184 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1185 -- subtype to the parameter and dereference cases, since other aliased
1186 -- objects are unconstrained (unless the nominal subtype is explicitly
1187 -- constrained).
1189 if Present (Lhs)
1190 and then (Present (Param_Entity (Lhs))
1191 or else (Ada_Version < Ada_05
1192 and then not Is_Constrained (T_Typ)
1193 and then Is_Aliased_View (Lhs)
1194 and then not Is_Aliased_Unconstrained_Component)
1195 or else (Ada_Version >= Ada_05
1196 and then not Is_Constrained (T_Typ)
1197 and then Denotes_Explicit_Dereference (Lhs)
1198 and then Nkind (Original_Node (Lhs)) /=
1199 N_Function_Call))
1200 then
1201 T_Typ := Get_Actual_Subtype (Lhs);
1202 end if;
1204 -- Nothing to do if the type is unconstrained (this is the case where
1205 -- the actual subtype in the RM sense of N is unconstrained and no check
1206 -- is required).
1208 if not Is_Constrained (T_Typ) then
1209 return;
1211 -- Ada 2005: nothing to do if the type is one for which there is a
1212 -- partial view that is constrained.
1214 elsif Ada_Version >= Ada_05
1215 and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1216 then
1217 return;
1218 end if;
1220 -- Nothing to do if the type is an Unchecked_Union
1222 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1223 return;
1224 end if;
1226 -- Suppress checks if the subtypes are the same. the check must be
1227 -- preserved in an assignment to a formal, because the constraint is
1228 -- given by the actual.
1230 if Nkind (Original_Node (N)) /= N_Allocator
1231 and then (No (Lhs)
1232 or else not Is_Entity_Name (Lhs)
1233 or else No (Param_Entity (Lhs)))
1234 then
1235 if (Etype (N) = Typ
1236 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1237 and then not Is_Aliased_View (Lhs)
1238 then
1239 return;
1240 end if;
1242 -- We can also eliminate checks on allocators with a subtype mark that
1243 -- coincides with the context type. The context type may be a subtype
1244 -- without a constraint (common case, a generic actual).
1246 elsif Nkind (Original_Node (N)) = N_Allocator
1247 and then Is_Entity_Name (Expression (Original_Node (N)))
1248 then
1249 declare
1250 Alloc_Typ : constant Entity_Id :=
1251 Entity (Expression (Original_Node (N)));
1253 begin
1254 if Alloc_Typ = T_Typ
1255 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1256 and then Is_Entity_Name (
1257 Subtype_Indication (Parent (T_Typ)))
1258 and then Alloc_Typ = Base_Type (T_Typ))
1260 then
1261 return;
1262 end if;
1263 end;
1264 end if;
1266 -- See if we have a case where the types are both constrained, and all
1267 -- the constraints are constants. In this case, we can do the check
1268 -- successfully at compile time.
1270 -- We skip this check for the case where the node is a rewritten`
1271 -- allocator, because it already carries the context subtype, and
1272 -- extracting the discriminants from the aggregate is messy.
1274 if Is_Constrained (S_Typ)
1275 and then Nkind (Original_Node (N)) /= N_Allocator
1276 then
1277 declare
1278 DconT : Elmt_Id;
1279 Discr : Entity_Id;
1280 DconS : Elmt_Id;
1281 ItemS : Node_Id;
1282 ItemT : Node_Id;
1284 begin
1285 -- S_Typ may not have discriminants in the case where it is a
1286 -- private type completed by a default discriminated type. In that
1287 -- case, we need to get the constraints from the underlying_type.
1288 -- If the underlying type is unconstrained (i.e. has no default
1289 -- discriminants) no check is needed.
1291 if Has_Discriminants (S_Typ) then
1292 Discr := First_Discriminant (S_Typ);
1293 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1295 else
1296 Discr := First_Discriminant (Underlying_Type (S_Typ));
1297 DconS :=
1298 First_Elmt
1299 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1301 if No (DconS) then
1302 return;
1303 end if;
1305 -- A further optimization: if T_Typ is derived from S_Typ
1306 -- without imposing a constraint, no check is needed.
1308 if Nkind (Original_Node (Parent (T_Typ))) =
1309 N_Full_Type_Declaration
1310 then
1311 declare
1312 Type_Def : constant Node_Id :=
1313 Type_Definition
1314 (Original_Node (Parent (T_Typ)));
1315 begin
1316 if Nkind (Type_Def) = N_Derived_Type_Definition
1317 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1318 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1319 then
1320 return;
1321 end if;
1322 end;
1323 end if;
1324 end if;
1326 DconT := First_Elmt (Discriminant_Constraint (T_Typ));
1328 while Present (Discr) loop
1329 ItemS := Node (DconS);
1330 ItemT := Node (DconT);
1332 -- For a discriminated component type constrained by the
1333 -- current instance of an enclosing type, there is no
1334 -- applicable discriminant check.
1336 if Nkind (ItemT) = N_Attribute_Reference
1337 and then Is_Access_Type (Etype (ItemT))
1338 and then Is_Entity_Name (Prefix (ItemT))
1339 and then Is_Type (Entity (Prefix (ItemT)))
1340 then
1341 return;
1342 end if;
1344 -- If the expressions for the discriminants are identical
1345 -- and it is side-effect free (for now just an entity),
1346 -- this may be a shared constraint, e.g. from a subtype
1347 -- without a constraint introduced as a generic actual.
1348 -- Examine other discriminants if any.
1350 if ItemS = ItemT
1351 and then Is_Entity_Name (ItemS)
1352 then
1353 null;
1355 elsif not Is_OK_Static_Expression (ItemS)
1356 or else not Is_OK_Static_Expression (ItemT)
1357 then
1358 exit;
1360 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1361 if Do_Access then -- needs run-time check.
1362 exit;
1363 else
1364 Apply_Compile_Time_Constraint_Error
1365 (N, "incorrect value for discriminant&?",
1366 CE_Discriminant_Check_Failed, Ent => Discr);
1367 return;
1368 end if;
1369 end if;
1371 Next_Elmt (DconS);
1372 Next_Elmt (DconT);
1373 Next_Discriminant (Discr);
1374 end loop;
1376 if No (Discr) then
1377 return;
1378 end if;
1379 end;
1380 end if;
1382 -- Here we need a discriminant check. First build the expression
1383 -- for the comparisons of the discriminants:
1385 -- (n.disc1 /= typ.disc1) or else
1386 -- (n.disc2 /= typ.disc2) or else
1387 -- ...
1388 -- (n.discn /= typ.discn)
1390 Cond := Build_Discriminant_Checks (N, T_Typ);
1392 -- If Lhs is set and is a parameter, then the condition is
1393 -- guarded by: lhs'constrained and then (condition built above)
1395 if Present (Param_Entity (Lhs)) then
1396 Cond :=
1397 Make_And_Then (Loc,
1398 Left_Opnd =>
1399 Make_Attribute_Reference (Loc,
1400 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1401 Attribute_Name => Name_Constrained),
1402 Right_Opnd => Cond);
1403 end if;
1405 if Do_Access then
1406 Cond := Guard_Access (Cond, Loc, N);
1407 end if;
1409 Insert_Action (N,
1410 Make_Raise_Constraint_Error (Loc,
1411 Condition => Cond,
1412 Reason => CE_Discriminant_Check_Failed));
1413 end Apply_Discriminant_Check;
1415 ------------------------
1416 -- Apply_Divide_Check --
1417 ------------------------
1419 procedure Apply_Divide_Check (N : Node_Id) is
1420 Loc : constant Source_Ptr := Sloc (N);
1421 Typ : constant Entity_Id := Etype (N);
1422 Left : constant Node_Id := Left_Opnd (N);
1423 Right : constant Node_Id := Right_Opnd (N);
1425 LLB : Uint;
1426 Llo : Uint;
1427 Lhi : Uint;
1428 LOK : Boolean;
1429 Rlo : Uint;
1430 Rhi : Uint;
1431 ROK : Boolean;
1433 pragma Warnings (Off, Lhi);
1434 -- Don't actually use this value
1436 begin
1437 if Expander_Active
1438 and then not Backend_Divide_Checks_On_Target
1439 and then Check_Needed (Right, Division_Check)
1440 then
1441 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1443 -- See if division by zero possible, and if so generate test. This
1444 -- part of the test is not controlled by the -gnato switch.
1446 if Do_Division_Check (N) then
1447 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1448 Insert_Action (N,
1449 Make_Raise_Constraint_Error (Loc,
1450 Condition =>
1451 Make_Op_Eq (Loc,
1452 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1453 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1454 Reason => CE_Divide_By_Zero));
1455 end if;
1456 end if;
1458 -- Test for extremely annoying case of xxx'First divided by -1
1460 if Do_Overflow_Check (N) then
1461 if Nkind (N) = N_Op_Divide
1462 and then Is_Signed_Integer_Type (Typ)
1463 then
1464 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1465 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1467 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1468 and then
1469 ((not LOK) or else (Llo = LLB))
1470 then
1471 Insert_Action (N,
1472 Make_Raise_Constraint_Error (Loc,
1473 Condition =>
1474 Make_And_Then (Loc,
1476 Make_Op_Eq (Loc,
1477 Left_Opnd =>
1478 Duplicate_Subexpr_Move_Checks (Left),
1479 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1481 Make_Op_Eq (Loc,
1482 Left_Opnd =>
1483 Duplicate_Subexpr (Right),
1484 Right_Opnd =>
1485 Make_Integer_Literal (Loc, -1))),
1486 Reason => CE_Overflow_Check_Failed));
1487 end if;
1488 end if;
1489 end if;
1490 end if;
1491 end Apply_Divide_Check;
1493 ----------------------------------
1494 -- Apply_Float_Conversion_Check --
1495 ----------------------------------
1497 -- Let F and I be the source and target types of the conversion. The RM
1498 -- specifies that a floating-point value X is rounded to the nearest
1499 -- integer, with halfway cases being rounded away from zero. The rounded
1500 -- value of X is checked against I'Range.
1502 -- The catch in the above paragraph is that there is no good way to know
1503 -- whether the round-to-integer operation resulted in overflow. A remedy is
1504 -- to perform a range check in the floating-point domain instead, however:
1506 -- (1) The bounds may not be known at compile time
1507 -- (2) The check must take into account rounding or truncation.
1508 -- (3) The range of type I may not be exactly representable in F.
1509 -- (4) For the rounding case, The end-points I'First - 0.5 and
1510 -- I'Last + 0.5 may or may not be in range, depending on the
1511 -- sign of I'First and I'Last.
1512 -- (5) X may be a NaN, which will fail any comparison
1514 -- The following steps correctly convert X with rounding:
1516 -- (1) If either I'First or I'Last is not known at compile time, use
1517 -- I'Base instead of I in the next three steps and perform a
1518 -- regular range check against I'Range after conversion.
1519 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1520 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1521 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1522 -- In other words, take one of the closest floating-point numbers
1523 -- (which is an integer value) to I'First, and see if it is in
1524 -- range or not.
1525 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1526 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1527 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1528 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1529 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1531 -- For the truncating case, replace steps (2) and (3) as follows:
1532 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1533 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1534 -- Lo_OK be True.
1535 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1536 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1537 -- Hi_OK be False
1539 procedure Apply_Float_Conversion_Check
1540 (Ck_Node : Node_Id;
1541 Target_Typ : Entity_Id)
1543 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1544 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1545 Loc : constant Source_Ptr := Sloc (Ck_Node);
1546 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1547 Target_Base : constant Entity_Id :=
1548 Implementation_Base_Type (Target_Typ);
1550 Par : constant Node_Id := Parent (Ck_Node);
1551 pragma Assert (Nkind (Par) = N_Type_Conversion);
1552 -- Parent of check node, must be a type conversion
1554 Truncate : constant Boolean := Float_Truncate (Par);
1555 Max_Bound : constant Uint :=
1556 UI_Expon
1557 (Machine_Radix (Expr_Type),
1558 Machine_Mantissa (Expr_Type) - 1) - 1;
1560 -- Largest bound, so bound plus or minus half is a machine number of F
1562 Ifirst, Ilast : Uint;
1563 -- Bounds of integer type
1565 Lo, Hi : Ureal;
1566 -- Bounds to check in floating-point domain
1568 Lo_OK, Hi_OK : Boolean;
1569 -- True iff Lo resp. Hi belongs to I'Range
1571 Lo_Chk, Hi_Chk : Node_Id;
1572 -- Expressions that are False iff check fails
1574 Reason : RT_Exception_Code;
1576 begin
1577 if not Compile_Time_Known_Value (LB)
1578 or not Compile_Time_Known_Value (HB)
1579 then
1580 declare
1581 -- First check that the value falls in the range of the base type,
1582 -- to prevent overflow during conversion and then perform a
1583 -- regular range check against the (dynamic) bounds.
1585 pragma Assert (Target_Base /= Target_Typ);
1587 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
1589 begin
1590 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1591 Set_Etype (Temp, Target_Base);
1593 Insert_Action (Parent (Par),
1594 Make_Object_Declaration (Loc,
1595 Defining_Identifier => Temp,
1596 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1597 Expression => New_Copy_Tree (Par)),
1598 Suppress => All_Checks);
1600 Insert_Action (Par,
1601 Make_Raise_Constraint_Error (Loc,
1602 Condition =>
1603 Make_Not_In (Loc,
1604 Left_Opnd => New_Occurrence_Of (Temp, Loc),
1605 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1606 Reason => CE_Range_Check_Failed));
1607 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1609 return;
1610 end;
1611 end if;
1613 -- Get the (static) bounds of the target type
1615 Ifirst := Expr_Value (LB);
1616 Ilast := Expr_Value (HB);
1618 -- A simple optimization: if the expression is a universal literal,
1619 -- we can do the comparison with the bounds and the conversion to
1620 -- an integer type statically. The range checks are unchanged.
1622 if Nkind (Ck_Node) = N_Real_Literal
1623 and then Etype (Ck_Node) = Universal_Real
1624 and then Is_Integer_Type (Target_Typ)
1625 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
1626 then
1627 declare
1628 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
1630 begin
1631 if Int_Val <= Ilast and then Int_Val >= Ifirst then
1633 -- Conversion is safe
1635 Rewrite (Parent (Ck_Node),
1636 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
1637 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
1638 return;
1639 end if;
1640 end;
1641 end if;
1643 -- Check against lower bound
1645 if Truncate and then Ifirst > 0 then
1646 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1647 Lo_OK := False;
1649 elsif Truncate then
1650 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1651 Lo_OK := True;
1653 elsif abs (Ifirst) < Max_Bound then
1654 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1655 Lo_OK := (Ifirst > 0);
1657 else
1658 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1659 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1660 end if;
1662 if Lo_OK then
1664 -- Lo_Chk := (X >= Lo)
1666 Lo_Chk := Make_Op_Ge (Loc,
1667 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1668 Right_Opnd => Make_Real_Literal (Loc, Lo));
1670 else
1671 -- Lo_Chk := (X > Lo)
1673 Lo_Chk := Make_Op_Gt (Loc,
1674 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1675 Right_Opnd => Make_Real_Literal (Loc, Lo));
1676 end if;
1678 -- Check against higher bound
1680 if Truncate and then Ilast < 0 then
1681 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1682 Lo_OK := False;
1684 elsif Truncate then
1685 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1686 Hi_OK := True;
1688 elsif abs (Ilast) < Max_Bound then
1689 Hi := UR_From_Uint (Ilast) + Ureal_Half;
1690 Hi_OK := (Ilast < 0);
1691 else
1692 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1693 Hi_OK := (Hi <= UR_From_Uint (Ilast));
1694 end if;
1696 if Hi_OK then
1698 -- Hi_Chk := (X <= Hi)
1700 Hi_Chk := Make_Op_Le (Loc,
1701 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1702 Right_Opnd => Make_Real_Literal (Loc, Hi));
1704 else
1705 -- Hi_Chk := (X < Hi)
1707 Hi_Chk := Make_Op_Lt (Loc,
1708 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1709 Right_Opnd => Make_Real_Literal (Loc, Hi));
1710 end if;
1712 -- If the bounds of the target type are the same as those of the base
1713 -- type, the check is an overflow check as a range check is not
1714 -- performed in these cases.
1716 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1717 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1718 then
1719 Reason := CE_Overflow_Check_Failed;
1720 else
1721 Reason := CE_Range_Check_Failed;
1722 end if;
1724 -- Raise CE if either conditions does not hold
1726 Insert_Action (Ck_Node,
1727 Make_Raise_Constraint_Error (Loc,
1728 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1729 Reason => Reason));
1730 end Apply_Float_Conversion_Check;
1732 ------------------------
1733 -- Apply_Length_Check --
1734 ------------------------
1736 procedure Apply_Length_Check
1737 (Ck_Node : Node_Id;
1738 Target_Typ : Entity_Id;
1739 Source_Typ : Entity_Id := Empty)
1741 begin
1742 Apply_Selected_Length_Checks
1743 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1744 end Apply_Length_Check;
1746 -----------------------
1747 -- Apply_Range_Check --
1748 -----------------------
1750 procedure Apply_Range_Check
1751 (Ck_Node : Node_Id;
1752 Target_Typ : Entity_Id;
1753 Source_Typ : Entity_Id := Empty)
1755 begin
1756 Apply_Selected_Range_Checks
1757 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1758 end Apply_Range_Check;
1760 ------------------------------
1761 -- Apply_Scalar_Range_Check --
1762 ------------------------------
1764 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1765 -- off if it is already set on.
1767 procedure Apply_Scalar_Range_Check
1768 (Expr : Node_Id;
1769 Target_Typ : Entity_Id;
1770 Source_Typ : Entity_Id := Empty;
1771 Fixed_Int : Boolean := False)
1773 Parnt : constant Node_Id := Parent (Expr);
1774 S_Typ : Entity_Id;
1775 Arr : Node_Id := Empty; -- initialize to prevent warning
1776 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
1777 OK : Boolean;
1779 Is_Subscr_Ref : Boolean;
1780 -- Set true if Expr is a subscript
1782 Is_Unconstrained_Subscr_Ref : Boolean;
1783 -- Set true if Expr is a subscript of an unconstrained array. In this
1784 -- case we do not attempt to do an analysis of the value against the
1785 -- range of the subscript, since we don't know the actual subtype.
1787 Int_Real : Boolean;
1788 -- Set to True if Expr should be regarded as a real value even though
1789 -- the type of Expr might be discrete.
1791 procedure Bad_Value;
1792 -- Procedure called if value is determined to be out of range
1794 ---------------
1795 -- Bad_Value --
1796 ---------------
1798 procedure Bad_Value is
1799 begin
1800 Apply_Compile_Time_Constraint_Error
1801 (Expr, "value not in range of}?", CE_Range_Check_Failed,
1802 Ent => Target_Typ,
1803 Typ => Target_Typ);
1804 end Bad_Value;
1806 -- Start of processing for Apply_Scalar_Range_Check
1808 begin
1809 -- Return if check obviously not needed
1812 -- Not needed inside generic
1814 Inside_A_Generic
1816 -- Not needed if previous error
1818 or else Target_Typ = Any_Type
1819 or else Nkind (Expr) = N_Error
1821 -- Not needed for non-scalar type
1823 or else not Is_Scalar_Type (Target_Typ)
1825 -- Not needed if we know node raises CE already
1827 or else Raises_Constraint_Error (Expr)
1828 then
1829 return;
1830 end if;
1832 -- Now, see if checks are suppressed
1834 Is_Subscr_Ref :=
1835 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1837 if Is_Subscr_Ref then
1838 Arr := Prefix (Parnt);
1839 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1840 end if;
1842 if not Do_Range_Check (Expr) then
1844 -- Subscript reference. Check for Index_Checks suppressed
1846 if Is_Subscr_Ref then
1848 -- Check array type and its base type
1850 if Index_Checks_Suppressed (Arr_Typ)
1851 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1852 then
1853 return;
1855 -- Check array itself if it is an entity name
1857 elsif Is_Entity_Name (Arr)
1858 and then Index_Checks_Suppressed (Entity (Arr))
1859 then
1860 return;
1862 -- Check expression itself if it is an entity name
1864 elsif Is_Entity_Name (Expr)
1865 and then Index_Checks_Suppressed (Entity (Expr))
1866 then
1867 return;
1868 end if;
1870 -- All other cases, check for Range_Checks suppressed
1872 else
1873 -- Check target type and its base type
1875 if Range_Checks_Suppressed (Target_Typ)
1876 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1877 then
1878 return;
1880 -- Check expression itself if it is an entity name
1882 elsif Is_Entity_Name (Expr)
1883 and then Range_Checks_Suppressed (Entity (Expr))
1884 then
1885 return;
1887 -- If Expr is part of an assignment statement, then check left
1888 -- side of assignment if it is an entity name.
1890 elsif Nkind (Parnt) = N_Assignment_Statement
1891 and then Is_Entity_Name (Name (Parnt))
1892 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1893 then
1894 return;
1895 end if;
1896 end if;
1897 end if;
1899 -- Do not set range checks if they are killed
1901 if Nkind (Expr) = N_Unchecked_Type_Conversion
1902 and then Kill_Range_Check (Expr)
1903 then
1904 return;
1905 end if;
1907 -- Do not set range checks for any values from System.Scalar_Values
1908 -- since the whole idea of such values is to avoid checking them!
1910 if Is_Entity_Name (Expr)
1911 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1912 then
1913 return;
1914 end if;
1916 -- Now see if we need a check
1918 if No (Source_Typ) then
1919 S_Typ := Etype (Expr);
1920 else
1921 S_Typ := Source_Typ;
1922 end if;
1924 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1925 return;
1926 end if;
1928 Is_Unconstrained_Subscr_Ref :=
1929 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1931 -- Always do a range check if the source type includes infinities and
1932 -- the target type does not include infinities. We do not do this if
1933 -- range checks are killed.
1935 if Is_Floating_Point_Type (S_Typ)
1936 and then Has_Infinities (S_Typ)
1937 and then not Has_Infinities (Target_Typ)
1938 then
1939 Enable_Range_Check (Expr);
1940 end if;
1942 -- Return if we know expression is definitely in the range of the target
1943 -- type as determined by Determine_Range. Right now we only do this for
1944 -- discrete types, and not fixed-point or floating-point types.
1946 -- The additional less-precise tests below catch these cases
1948 -- Note: skip this if we are given a source_typ, since the point of
1949 -- supplying a Source_Typ is to stop us looking at the expression.
1950 -- We could sharpen this test to be out parameters only ???
1952 if Is_Discrete_Type (Target_Typ)
1953 and then Is_Discrete_Type (Etype (Expr))
1954 and then not Is_Unconstrained_Subscr_Ref
1955 and then No (Source_Typ)
1956 then
1957 declare
1958 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
1959 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1960 Lo : Uint;
1961 Hi : Uint;
1963 begin
1964 if Compile_Time_Known_Value (Tlo)
1965 and then Compile_Time_Known_Value (Thi)
1966 then
1967 declare
1968 Lov : constant Uint := Expr_Value (Tlo);
1969 Hiv : constant Uint := Expr_Value (Thi);
1971 begin
1972 -- If range is null, we for sure have a constraint error
1973 -- (we don't even need to look at the value involved,
1974 -- since all possible values will raise CE).
1976 if Lov > Hiv then
1977 Bad_Value;
1978 return;
1979 end if;
1981 -- Otherwise determine range of value
1983 Determine_Range (Expr, OK, Lo, Hi, Assume_Valid => True);
1985 if OK then
1987 -- If definitely in range, all OK
1989 if Lo >= Lov and then Hi <= Hiv then
1990 return;
1992 -- If definitely not in range, warn
1994 elsif Lov > Hi or else Hiv < Lo then
1995 Bad_Value;
1996 return;
1998 -- Otherwise we don't know
2000 else
2001 null;
2002 end if;
2003 end if;
2004 end;
2005 end if;
2006 end;
2007 end if;
2009 Int_Real :=
2010 Is_Floating_Point_Type (S_Typ)
2011 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
2013 -- Check if we can determine at compile time whether Expr is in the
2014 -- range of the target type. Note that if S_Typ is within the bounds
2015 -- of Target_Typ then this must be the case. This check is meaningful
2016 -- only if this is not a conversion between integer and real types.
2018 if not Is_Unconstrained_Subscr_Ref
2019 and then
2020 Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
2021 and then
2022 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
2023 or else
2024 Is_In_Range (Expr, Target_Typ,
2025 Assume_Valid => True,
2026 Fixed_Int => Fixed_Int,
2027 Int_Real => Int_Real))
2028 then
2029 return;
2031 elsif Is_Out_Of_Range (Expr, Target_Typ,
2032 Assume_Valid => True,
2033 Fixed_Int => Fixed_Int,
2034 Int_Real => Int_Real)
2035 then
2036 Bad_Value;
2037 return;
2039 -- In the floating-point case, we only do range checks if the type is
2040 -- constrained. We definitely do NOT want range checks for unconstrained
2041 -- types, since we want to have infinities
2043 elsif Is_Floating_Point_Type (S_Typ) then
2044 if Is_Constrained (S_Typ) then
2045 Enable_Range_Check (Expr);
2046 end if;
2048 -- For all other cases we enable a range check unconditionally
2050 else
2051 Enable_Range_Check (Expr);
2052 return;
2053 end if;
2054 end Apply_Scalar_Range_Check;
2056 ----------------------------------
2057 -- Apply_Selected_Length_Checks --
2058 ----------------------------------
2060 procedure Apply_Selected_Length_Checks
2061 (Ck_Node : Node_Id;
2062 Target_Typ : Entity_Id;
2063 Source_Typ : Entity_Id;
2064 Do_Static : Boolean)
2066 Cond : Node_Id;
2067 R_Result : Check_Result;
2068 R_Cno : Node_Id;
2070 Loc : constant Source_Ptr := Sloc (Ck_Node);
2071 Checks_On : constant Boolean :=
2072 (not Index_Checks_Suppressed (Target_Typ))
2073 or else
2074 (not Length_Checks_Suppressed (Target_Typ));
2076 begin
2077 if not Expander_Active then
2078 return;
2079 end if;
2081 R_Result :=
2082 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2084 for J in 1 .. 2 loop
2085 R_Cno := R_Result (J);
2086 exit when No (R_Cno);
2088 -- A length check may mention an Itype which is attached to a
2089 -- subsequent node. At the top level in a package this can cause
2090 -- an order-of-elaboration problem, so we make sure that the itype
2091 -- is referenced now.
2093 if Ekind (Current_Scope) = E_Package
2094 and then Is_Compilation_Unit (Current_Scope)
2095 then
2096 Ensure_Defined (Target_Typ, Ck_Node);
2098 if Present (Source_Typ) then
2099 Ensure_Defined (Source_Typ, Ck_Node);
2101 elsif Is_Itype (Etype (Ck_Node)) then
2102 Ensure_Defined (Etype (Ck_Node), Ck_Node);
2103 end if;
2104 end if;
2106 -- If the item is a conditional raise of constraint error, then have
2107 -- a look at what check is being performed and ???
2109 if Nkind (R_Cno) = N_Raise_Constraint_Error
2110 and then Present (Condition (R_Cno))
2111 then
2112 Cond := Condition (R_Cno);
2114 -- Case where node does not now have a dynamic check
2116 if not Has_Dynamic_Length_Check (Ck_Node) then
2118 -- If checks are on, just insert the check
2120 if Checks_On then
2121 Insert_Action (Ck_Node, R_Cno);
2123 if not Do_Static then
2124 Set_Has_Dynamic_Length_Check (Ck_Node);
2125 end if;
2127 -- If checks are off, then analyze the length check after
2128 -- temporarily attaching it to the tree in case the relevant
2129 -- condition can be evaluted at compile time. We still want a
2130 -- compile time warning in this case.
2132 else
2133 Set_Parent (R_Cno, Ck_Node);
2134 Analyze (R_Cno);
2135 end if;
2136 end if;
2138 -- Output a warning if the condition is known to be True
2140 if Is_Entity_Name (Cond)
2141 and then Entity (Cond) = Standard_True
2142 then
2143 Apply_Compile_Time_Constraint_Error
2144 (Ck_Node, "wrong length for array of}?",
2145 CE_Length_Check_Failed,
2146 Ent => Target_Typ,
2147 Typ => Target_Typ);
2149 -- If we were only doing a static check, or if checks are not
2150 -- on, then we want to delete the check, since it is not needed.
2151 -- We do this by replacing the if statement by a null statement
2153 elsif Do_Static or else not Checks_On then
2154 Remove_Warning_Messages (R_Cno);
2155 Rewrite (R_Cno, Make_Null_Statement (Loc));
2156 end if;
2158 else
2159 Install_Static_Check (R_Cno, Loc);
2160 end if;
2161 end loop;
2162 end Apply_Selected_Length_Checks;
2164 ---------------------------------
2165 -- Apply_Selected_Range_Checks --
2166 ---------------------------------
2168 procedure Apply_Selected_Range_Checks
2169 (Ck_Node : Node_Id;
2170 Target_Typ : Entity_Id;
2171 Source_Typ : Entity_Id;
2172 Do_Static : Boolean)
2174 Cond : Node_Id;
2175 R_Result : Check_Result;
2176 R_Cno : Node_Id;
2178 Loc : constant Source_Ptr := Sloc (Ck_Node);
2179 Checks_On : constant Boolean :=
2180 (not Index_Checks_Suppressed (Target_Typ))
2181 or else
2182 (not Range_Checks_Suppressed (Target_Typ));
2184 begin
2185 if not Expander_Active or else not Checks_On then
2186 return;
2187 end if;
2189 R_Result :=
2190 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2192 for J in 1 .. 2 loop
2194 R_Cno := R_Result (J);
2195 exit when No (R_Cno);
2197 -- If the item is a conditional raise of constraint error, then have
2198 -- a look at what check is being performed and ???
2200 if Nkind (R_Cno) = N_Raise_Constraint_Error
2201 and then Present (Condition (R_Cno))
2202 then
2203 Cond := Condition (R_Cno);
2205 if not Has_Dynamic_Range_Check (Ck_Node) then
2206 Insert_Action (Ck_Node, R_Cno);
2208 if not Do_Static then
2209 Set_Has_Dynamic_Range_Check (Ck_Node);
2210 end if;
2211 end if;
2213 -- Output a warning if the condition is known to be True
2215 if Is_Entity_Name (Cond)
2216 and then Entity (Cond) = Standard_True
2217 then
2218 -- Since an N_Range is technically not an expression, we have
2219 -- to set one of the bounds to C_E and then just flag the
2220 -- N_Range. The warning message will point to the lower bound
2221 -- and complain about a range, which seems OK.
2223 if Nkind (Ck_Node) = N_Range then
2224 Apply_Compile_Time_Constraint_Error
2225 (Low_Bound (Ck_Node), "static range out of bounds of}?",
2226 CE_Range_Check_Failed,
2227 Ent => Target_Typ,
2228 Typ => Target_Typ);
2230 Set_Raises_Constraint_Error (Ck_Node);
2232 else
2233 Apply_Compile_Time_Constraint_Error
2234 (Ck_Node, "static value out of range of}?",
2235 CE_Range_Check_Failed,
2236 Ent => Target_Typ,
2237 Typ => Target_Typ);
2238 end if;
2240 -- If we were only doing a static check, or if checks are not
2241 -- on, then we want to delete the check, since it is not needed.
2242 -- We do this by replacing the if statement by a null statement
2244 elsif Do_Static or else not Checks_On then
2245 Remove_Warning_Messages (R_Cno);
2246 Rewrite (R_Cno, Make_Null_Statement (Loc));
2247 end if;
2249 else
2250 Install_Static_Check (R_Cno, Loc);
2251 end if;
2252 end loop;
2253 end Apply_Selected_Range_Checks;
2255 -------------------------------
2256 -- Apply_Static_Length_Check --
2257 -------------------------------
2259 procedure Apply_Static_Length_Check
2260 (Expr : Node_Id;
2261 Target_Typ : Entity_Id;
2262 Source_Typ : Entity_Id := Empty)
2264 begin
2265 Apply_Selected_Length_Checks
2266 (Expr, Target_Typ, Source_Typ, Do_Static => True);
2267 end Apply_Static_Length_Check;
2269 -------------------------------------
2270 -- Apply_Subscript_Validity_Checks --
2271 -------------------------------------
2273 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2274 Sub : Node_Id;
2276 begin
2277 pragma Assert (Nkind (Expr) = N_Indexed_Component);
2279 -- Loop through subscripts
2281 Sub := First (Expressions (Expr));
2282 while Present (Sub) loop
2284 -- Check one subscript. Note that we do not worry about enumeration
2285 -- type with holes, since we will convert the value to a Pos value
2286 -- for the subscript, and that convert will do the necessary validity
2287 -- check.
2289 Ensure_Valid (Sub, Holes_OK => True);
2291 -- Move to next subscript
2293 Sub := Next (Sub);
2294 end loop;
2295 end Apply_Subscript_Validity_Checks;
2297 ----------------------------------
2298 -- Apply_Type_Conversion_Checks --
2299 ----------------------------------
2301 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2302 Target_Type : constant Entity_Id := Etype (N);
2303 Target_Base : constant Entity_Id := Base_Type (Target_Type);
2304 Expr : constant Node_Id := Expression (N);
2305 Expr_Type : constant Entity_Id := Etype (Expr);
2307 begin
2308 if Inside_A_Generic then
2309 return;
2311 -- Skip these checks if serious errors detected, there are some nasty
2312 -- situations of incomplete trees that blow things up.
2314 elsif Serious_Errors_Detected > 0 then
2315 return;
2317 -- Scalar type conversions of the form Target_Type (Expr) require a
2318 -- range check if we cannot be sure that Expr is in the base type of
2319 -- Target_Typ and also that Expr is in the range of Target_Typ. These
2320 -- are not quite the same condition from an implementation point of
2321 -- view, but clearly the second includes the first.
2323 elsif Is_Scalar_Type (Target_Type) then
2324 declare
2325 Conv_OK : constant Boolean := Conversion_OK (N);
2326 -- If the Conversion_OK flag on the type conversion is set and no
2327 -- floating point type is involved in the type conversion then
2328 -- fixed point values must be read as integral values.
2330 Float_To_Int : constant Boolean :=
2331 Is_Floating_Point_Type (Expr_Type)
2332 and then Is_Integer_Type (Target_Type);
2334 begin
2335 if not Overflow_Checks_Suppressed (Target_Base)
2336 and then not
2337 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
2338 and then not Float_To_Int
2339 then
2340 Activate_Overflow_Check (N);
2341 end if;
2343 if not Range_Checks_Suppressed (Target_Type)
2344 and then not Range_Checks_Suppressed (Expr_Type)
2345 then
2346 if Float_To_Int then
2347 Apply_Float_Conversion_Check (Expr, Target_Type);
2348 else
2349 Apply_Scalar_Range_Check
2350 (Expr, Target_Type, Fixed_Int => Conv_OK);
2351 end if;
2352 end if;
2353 end;
2355 elsif Comes_From_Source (N)
2356 and then not Discriminant_Checks_Suppressed (Target_Type)
2357 and then Is_Record_Type (Target_Type)
2358 and then Is_Derived_Type (Target_Type)
2359 and then not Is_Tagged_Type (Target_Type)
2360 and then not Is_Constrained (Target_Type)
2361 and then Present (Stored_Constraint (Target_Type))
2362 then
2363 -- An unconstrained derived type may have inherited discriminant
2364 -- Build an actual discriminant constraint list using the stored
2365 -- constraint, to verify that the expression of the parent type
2366 -- satisfies the constraints imposed by the (unconstrained!)
2367 -- derived type. This applies to value conversions, not to view
2368 -- conversions of tagged types.
2370 declare
2371 Loc : constant Source_Ptr := Sloc (N);
2372 Cond : Node_Id;
2373 Constraint : Elmt_Id;
2374 Discr_Value : Node_Id;
2375 Discr : Entity_Id;
2377 New_Constraints : constant Elist_Id := New_Elmt_List;
2378 Old_Constraints : constant Elist_Id :=
2379 Discriminant_Constraint (Expr_Type);
2381 begin
2382 Constraint := First_Elmt (Stored_Constraint (Target_Type));
2383 while Present (Constraint) loop
2384 Discr_Value := Node (Constraint);
2386 if Is_Entity_Name (Discr_Value)
2387 and then Ekind (Entity (Discr_Value)) = E_Discriminant
2388 then
2389 Discr := Corresponding_Discriminant (Entity (Discr_Value));
2391 if Present (Discr)
2392 and then Scope (Discr) = Base_Type (Expr_Type)
2393 then
2394 -- Parent is constrained by new discriminant. Obtain
2395 -- Value of original discriminant in expression. If the
2396 -- new discriminant has been used to constrain more than
2397 -- one of the stored discriminants, this will provide the
2398 -- required consistency check.
2400 Append_Elmt (
2401 Make_Selected_Component (Loc,
2402 Prefix =>
2403 Duplicate_Subexpr_No_Checks
2404 (Expr, Name_Req => True),
2405 Selector_Name =>
2406 Make_Identifier (Loc, Chars (Discr))),
2407 New_Constraints);
2409 else
2410 -- Discriminant of more remote ancestor ???
2412 return;
2413 end if;
2415 -- Derived type definition has an explicit value for this
2416 -- stored discriminant.
2418 else
2419 Append_Elmt
2420 (Duplicate_Subexpr_No_Checks (Discr_Value),
2421 New_Constraints);
2422 end if;
2424 Next_Elmt (Constraint);
2425 end loop;
2427 -- Use the unconstrained expression type to retrieve the
2428 -- discriminants of the parent, and apply momentarily the
2429 -- discriminant constraint synthesized above.
2431 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2432 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2433 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2435 Insert_Action (N,
2436 Make_Raise_Constraint_Error (Loc,
2437 Condition => Cond,
2438 Reason => CE_Discriminant_Check_Failed));
2439 end;
2441 -- For arrays, conversions are applied during expansion, to take into
2442 -- accounts changes of representation. The checks become range checks on
2443 -- the base type or length checks on the subtype, depending on whether
2444 -- the target type is unconstrained or constrained.
2446 else
2447 null;
2448 end if;
2449 end Apply_Type_Conversion_Checks;
2451 ----------------------------------------------
2452 -- Apply_Universal_Integer_Attribute_Checks --
2453 ----------------------------------------------
2455 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2456 Loc : constant Source_Ptr := Sloc (N);
2457 Typ : constant Entity_Id := Etype (N);
2459 begin
2460 if Inside_A_Generic then
2461 return;
2463 -- Nothing to do if checks are suppressed
2465 elsif Range_Checks_Suppressed (Typ)
2466 and then Overflow_Checks_Suppressed (Typ)
2467 then
2468 return;
2470 -- Nothing to do if the attribute does not come from source. The
2471 -- internal attributes we generate of this type do not need checks,
2472 -- and furthermore the attempt to check them causes some circular
2473 -- elaboration orders when dealing with packed types.
2475 elsif not Comes_From_Source (N) then
2476 return;
2478 -- If the prefix is a selected component that depends on a discriminant
2479 -- the check may improperly expose a discriminant instead of using
2480 -- the bounds of the object itself. Set the type of the attribute to
2481 -- the base type of the context, so that a check will be imposed when
2482 -- needed (e.g. if the node appears as an index).
2484 elsif Nkind (Prefix (N)) = N_Selected_Component
2485 and then Ekind (Typ) = E_Signed_Integer_Subtype
2486 and then Depends_On_Discriminant (Scalar_Range (Typ))
2487 then
2488 Set_Etype (N, Base_Type (Typ));
2490 -- Otherwise, replace the attribute node with a type conversion node
2491 -- whose expression is the attribute, retyped to universal integer, and
2492 -- whose subtype mark is the target type. The call to analyze this
2493 -- conversion will set range and overflow checks as required for proper
2494 -- detection of an out of range value.
2496 else
2497 Set_Etype (N, Universal_Integer);
2498 Set_Analyzed (N, True);
2500 Rewrite (N,
2501 Make_Type_Conversion (Loc,
2502 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2503 Expression => Relocate_Node (N)));
2505 Analyze_And_Resolve (N, Typ);
2506 return;
2507 end if;
2508 end Apply_Universal_Integer_Attribute_Checks;
2510 -------------------------------
2511 -- Build_Discriminant_Checks --
2512 -------------------------------
2514 function Build_Discriminant_Checks
2515 (N : Node_Id;
2516 T_Typ : Entity_Id) return Node_Id
2518 Loc : constant Source_Ptr := Sloc (N);
2519 Cond : Node_Id;
2520 Disc : Elmt_Id;
2521 Disc_Ent : Entity_Id;
2522 Dref : Node_Id;
2523 Dval : Node_Id;
2525 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2527 ----------------------------------
2528 -- Aggregate_Discriminant_Value --
2529 ----------------------------------
2531 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2532 Assoc : Node_Id;
2534 begin
2535 -- The aggregate has been normalized with named associations. We use
2536 -- the Chars field to locate the discriminant to take into account
2537 -- discriminants in derived types, which carry the same name as those
2538 -- in the parent.
2540 Assoc := First (Component_Associations (N));
2541 while Present (Assoc) loop
2542 if Chars (First (Choices (Assoc))) = Chars (Disc) then
2543 return Expression (Assoc);
2544 else
2545 Next (Assoc);
2546 end if;
2547 end loop;
2549 -- Discriminant must have been found in the loop above
2551 raise Program_Error;
2552 end Aggregate_Discriminant_Val;
2554 -- Start of processing for Build_Discriminant_Checks
2556 begin
2557 -- Loop through discriminants evolving the condition
2559 Cond := Empty;
2560 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2562 -- For a fully private type, use the discriminants of the parent type
2564 if Is_Private_Type (T_Typ)
2565 and then No (Full_View (T_Typ))
2566 then
2567 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2568 else
2569 Disc_Ent := First_Discriminant (T_Typ);
2570 end if;
2572 while Present (Disc) loop
2573 Dval := Node (Disc);
2575 if Nkind (Dval) = N_Identifier
2576 and then Ekind (Entity (Dval)) = E_Discriminant
2577 then
2578 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2579 else
2580 Dval := Duplicate_Subexpr_No_Checks (Dval);
2581 end if;
2583 -- If we have an Unchecked_Union node, we can infer the discriminants
2584 -- of the node.
2586 if Is_Unchecked_Union (Base_Type (T_Typ)) then
2587 Dref := New_Copy (
2588 Get_Discriminant_Value (
2589 First_Discriminant (T_Typ),
2590 T_Typ,
2591 Stored_Constraint (T_Typ)));
2593 elsif Nkind (N) = N_Aggregate then
2594 Dref :=
2595 Duplicate_Subexpr_No_Checks
2596 (Aggregate_Discriminant_Val (Disc_Ent));
2598 else
2599 Dref :=
2600 Make_Selected_Component (Loc,
2601 Prefix =>
2602 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2603 Selector_Name =>
2604 Make_Identifier (Loc, Chars (Disc_Ent)));
2606 Set_Is_In_Discriminant_Check (Dref);
2607 end if;
2609 Evolve_Or_Else (Cond,
2610 Make_Op_Ne (Loc,
2611 Left_Opnd => Dref,
2612 Right_Opnd => Dval));
2614 Next_Elmt (Disc);
2615 Next_Discriminant (Disc_Ent);
2616 end loop;
2618 return Cond;
2619 end Build_Discriminant_Checks;
2621 ------------------
2622 -- Check_Needed --
2623 ------------------
2625 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2626 N : Node_Id;
2627 P : Node_Id;
2628 K : Node_Kind;
2629 L : Node_Id;
2630 R : Node_Id;
2632 begin
2633 -- Always check if not simple entity
2635 if Nkind (Nod) not in N_Has_Entity
2636 or else not Comes_From_Source (Nod)
2637 then
2638 return True;
2639 end if;
2641 -- Look up tree for short circuit
2643 N := Nod;
2644 loop
2645 P := Parent (N);
2646 K := Nkind (P);
2648 -- Done if out of subexpression (note that we allow generated stuff
2649 -- such as itype declarations in this context, to keep the loop going
2650 -- since we may well have generated such stuff in complex situations.
2651 -- Also done if no parent (probably an error condition, but no point
2652 -- in behaving nasty if we find it!)
2654 if No (P)
2655 or else (K not in N_Subexpr and then Comes_From_Source (P))
2656 then
2657 return True;
2659 -- Or/Or Else case, where test is part of the right operand, or is
2660 -- part of one of the actions associated with the right operand, and
2661 -- the left operand is an equality test.
2663 elsif K = N_Op_Or then
2664 exit when N = Right_Opnd (P)
2665 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2667 elsif K = N_Or_Else then
2668 exit when (N = Right_Opnd (P)
2669 or else
2670 (Is_List_Member (N)
2671 and then List_Containing (N) = Actions (P)))
2672 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2674 -- Similar test for the And/And then case, where the left operand
2675 -- is an inequality test.
2677 elsif K = N_Op_And then
2678 exit when N = Right_Opnd (P)
2679 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2681 elsif K = N_And_Then then
2682 exit when (N = Right_Opnd (P)
2683 or else
2684 (Is_List_Member (N)
2685 and then List_Containing (N) = Actions (P)))
2686 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2687 end if;
2689 N := P;
2690 end loop;
2692 -- If we fall through the loop, then we have a conditional with an
2693 -- appropriate test as its left operand. So test further.
2695 L := Left_Opnd (P);
2696 R := Right_Opnd (L);
2697 L := Left_Opnd (L);
2699 -- Left operand of test must match original variable
2701 if Nkind (L) not in N_Has_Entity
2702 or else Entity (L) /= Entity (Nod)
2703 then
2704 return True;
2705 end if;
2707 -- Right operand of test must be key value (zero or null)
2709 case Check is
2710 when Access_Check =>
2711 if not Known_Null (R) then
2712 return True;
2713 end if;
2715 when Division_Check =>
2716 if not Compile_Time_Known_Value (R)
2717 or else Expr_Value (R) /= Uint_0
2718 then
2719 return True;
2720 end if;
2722 when others =>
2723 raise Program_Error;
2724 end case;
2726 -- Here we have the optimizable case, warn if not short-circuited
2728 if K = N_Op_And or else K = N_Op_Or then
2729 case Check is
2730 when Access_Check =>
2731 Error_Msg_N
2732 ("Constraint_Error may be raised (access check)?",
2733 Parent (Nod));
2734 when Division_Check =>
2735 Error_Msg_N
2736 ("Constraint_Error may be raised (zero divide)?",
2737 Parent (Nod));
2739 when others =>
2740 raise Program_Error;
2741 end case;
2743 if K = N_Op_And then
2744 Error_Msg_N -- CODEFIX
2745 ("use `AND THEN` instead of AND?", P);
2746 else
2747 Error_Msg_N -- CODEFIX
2748 ("use `OR ELSE` instead of OR?", P);
2749 end if;
2751 -- If not short-circuited, we need the ckeck
2753 return True;
2755 -- If short-circuited, we can omit the check
2757 else
2758 return False;
2759 end if;
2760 end Check_Needed;
2762 -----------------------------------
2763 -- Check_Valid_Lvalue_Subscripts --
2764 -----------------------------------
2766 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2767 begin
2768 -- Skip this if range checks are suppressed
2770 if Range_Checks_Suppressed (Etype (Expr)) then
2771 return;
2773 -- Only do this check for expressions that come from source. We assume
2774 -- that expander generated assignments explicitly include any necessary
2775 -- checks. Note that this is not just an optimization, it avoids
2776 -- infinite recursions!
2778 elsif not Comes_From_Source (Expr) then
2779 return;
2781 -- For a selected component, check the prefix
2783 elsif Nkind (Expr) = N_Selected_Component then
2784 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2785 return;
2787 -- Case of indexed component
2789 elsif Nkind (Expr) = N_Indexed_Component then
2790 Apply_Subscript_Validity_Checks (Expr);
2792 -- Prefix may itself be or contain an indexed component, and these
2793 -- subscripts need checking as well.
2795 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2796 end if;
2797 end Check_Valid_Lvalue_Subscripts;
2799 ----------------------------------
2800 -- Null_Exclusion_Static_Checks --
2801 ----------------------------------
2803 procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2804 Error_Node : Node_Id;
2805 Expr : Node_Id;
2806 Has_Null : constant Boolean := Has_Null_Exclusion (N);
2807 K : constant Node_Kind := Nkind (N);
2808 Typ : Entity_Id;
2810 begin
2811 pragma Assert
2812 (K = N_Component_Declaration
2813 or else K = N_Discriminant_Specification
2814 or else K = N_Function_Specification
2815 or else K = N_Object_Declaration
2816 or else K = N_Parameter_Specification);
2818 if K = N_Function_Specification then
2819 Typ := Etype (Defining_Entity (N));
2820 else
2821 Typ := Etype (Defining_Identifier (N));
2822 end if;
2824 case K is
2825 when N_Component_Declaration =>
2826 if Present (Access_Definition (Component_Definition (N))) then
2827 Error_Node := Component_Definition (N);
2828 else
2829 Error_Node := Subtype_Indication (Component_Definition (N));
2830 end if;
2832 when N_Discriminant_Specification =>
2833 Error_Node := Discriminant_Type (N);
2835 when N_Function_Specification =>
2836 Error_Node := Result_Definition (N);
2838 when N_Object_Declaration =>
2839 Error_Node := Object_Definition (N);
2841 when N_Parameter_Specification =>
2842 Error_Node := Parameter_Type (N);
2844 when others =>
2845 raise Program_Error;
2846 end case;
2848 if Has_Null then
2850 -- Enforce legality rule 3.10 (13): A null exclusion can only be
2851 -- applied to an access [sub]type.
2853 if not Is_Access_Type (Typ) then
2854 Error_Msg_N
2855 ("`NOT NULL` allowed only for an access type", Error_Node);
2857 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
2858 -- be applied to a [sub]type that does not exclude null already.
2860 elsif Can_Never_Be_Null (Typ)
2861 and then Comes_From_Source (Typ)
2862 then
2863 Error_Msg_NE
2864 ("`NOT NULL` not allowed (& already excludes null)",
2865 Error_Node, Typ);
2866 end if;
2867 end if;
2869 -- Check that null-excluding objects are always initialized, except for
2870 -- deferred constants, for which the expression will appear in the full
2871 -- declaration.
2873 if K = N_Object_Declaration
2874 and then No (Expression (N))
2875 and then not Constant_Present (N)
2876 and then not No_Initialization (N)
2877 then
2878 -- Add an expression that assigns null. This node is needed by
2879 -- Apply_Compile_Time_Constraint_Error, which will replace this with
2880 -- a Constraint_Error node.
2882 Set_Expression (N, Make_Null (Sloc (N)));
2883 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2885 Apply_Compile_Time_Constraint_Error
2886 (N => Expression (N),
2887 Msg => "(Ada 2005) null-excluding objects must be initialized?",
2888 Reason => CE_Null_Not_Allowed);
2889 end if;
2891 -- Check that a null-excluding component, formal or object is not being
2892 -- assigned a null value. Otherwise generate a warning message and
2893 -- replace Expression (N) by an N_Constraint_Error node.
2895 if K /= N_Function_Specification then
2896 Expr := Expression (N);
2898 if Present (Expr) and then Known_Null (Expr) then
2899 case K is
2900 when N_Component_Declaration |
2901 N_Discriminant_Specification =>
2902 Apply_Compile_Time_Constraint_Error
2903 (N => Expr,
2904 Msg => "(Ada 2005) null not allowed " &
2905 "in null-excluding components?",
2906 Reason => CE_Null_Not_Allowed);
2908 when N_Object_Declaration =>
2909 Apply_Compile_Time_Constraint_Error
2910 (N => Expr,
2911 Msg => "(Ada 2005) null not allowed " &
2912 "in null-excluding objects?",
2913 Reason => CE_Null_Not_Allowed);
2915 when N_Parameter_Specification =>
2916 Apply_Compile_Time_Constraint_Error
2917 (N => Expr,
2918 Msg => "(Ada 2005) null not allowed " &
2919 "in null-excluding formals?",
2920 Reason => CE_Null_Not_Allowed);
2922 when others =>
2923 null;
2924 end case;
2925 end if;
2926 end if;
2927 end Null_Exclusion_Static_Checks;
2929 ----------------------------------
2930 -- Conditional_Statements_Begin --
2931 ----------------------------------
2933 procedure Conditional_Statements_Begin is
2934 begin
2935 Saved_Checks_TOS := Saved_Checks_TOS + 1;
2937 -- If stack overflows, kill all checks, that way we know to simply reset
2938 -- the number of saved checks to zero on return. This should never occur
2939 -- in practice.
2941 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2942 Kill_All_Checks;
2944 -- In the normal case, we just make a new stack entry saving the current
2945 -- number of saved checks for a later restore.
2947 else
2948 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2950 if Debug_Flag_CC then
2951 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2952 Num_Saved_Checks);
2953 end if;
2954 end if;
2955 end Conditional_Statements_Begin;
2957 --------------------------------
2958 -- Conditional_Statements_End --
2959 --------------------------------
2961 procedure Conditional_Statements_End is
2962 begin
2963 pragma Assert (Saved_Checks_TOS > 0);
2965 -- If the saved checks stack overflowed, then we killed all checks, so
2966 -- setting the number of saved checks back to zero is correct. This
2967 -- should never occur in practice.
2969 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2970 Num_Saved_Checks := 0;
2972 -- In the normal case, restore the number of saved checks from the top
2973 -- stack entry.
2975 else
2976 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
2977 if Debug_Flag_CC then
2978 w ("Conditional_Statements_End: Num_Saved_Checks = ",
2979 Num_Saved_Checks);
2980 end if;
2981 end if;
2983 Saved_Checks_TOS := Saved_Checks_TOS - 1;
2984 end Conditional_Statements_End;
2986 ---------------------
2987 -- Determine_Range --
2988 ---------------------
2990 Cache_Size : constant := 2 ** 10;
2991 type Cache_Index is range 0 .. Cache_Size - 1;
2992 -- Determine size of below cache (power of 2 is more efficient!)
2994 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
2995 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
2996 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
2997 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
2998 -- The above arrays are used to implement a small direct cache for
2999 -- Determine_Range calls. Because of the way Determine_Range recursively
3000 -- traces subexpressions, and because overflow checking calls the routine
3001 -- on the way up the tree, a quadratic behavior can otherwise be
3002 -- encountered in large expressions. The cache entry for node N is stored
3003 -- in the (N mod Cache_Size) entry, and can be validated by checking the
3004 -- actual node value stored there. The Range_Cache_V array records the
3005 -- setting of Assume_Valid for the cache entry.
3007 procedure Determine_Range
3008 (N : Node_Id;
3009 OK : out Boolean;
3010 Lo : out Uint;
3011 Hi : out Uint;
3012 Assume_Valid : Boolean := False)
3014 Typ : Entity_Id := Etype (N);
3015 -- Type to use, may get reset to base type for possibly invalid entity
3017 Lo_Left : Uint;
3018 Hi_Left : Uint;
3019 -- Lo and Hi bounds of left operand
3021 Lo_Right : Uint;
3022 Hi_Right : Uint;
3023 -- Lo and Hi bounds of right (or only) operand
3025 Bound : Node_Id;
3026 -- Temp variable used to hold a bound node
3028 Hbound : Uint;
3029 -- High bound of base type of expression
3031 Lor : Uint;
3032 Hir : Uint;
3033 -- Refined values for low and high bounds, after tightening
3035 OK1 : Boolean;
3036 -- Used in lower level calls to indicate if call succeeded
3038 Cindex : Cache_Index;
3039 -- Used to search cache
3041 function OK_Operands return Boolean;
3042 -- Used for binary operators. Determines the ranges of the left and
3043 -- right operands, and if they are both OK, returns True, and puts
3044 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
3046 -----------------
3047 -- OK_Operands --
3048 -----------------
3050 function OK_Operands return Boolean is
3051 begin
3052 Determine_Range
3053 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
3055 if not OK1 then
3056 return False;
3057 end if;
3059 Determine_Range
3060 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3061 return OK1;
3062 end OK_Operands;
3064 -- Start of processing for Determine_Range
3066 begin
3067 -- Prevent junk warnings by initializing range variables
3069 Lo := No_Uint;
3070 Hi := No_Uint;
3071 Lor := No_Uint;
3072 Hir := No_Uint;
3074 -- If type is not defined, we can't determine its range
3076 if No (Typ)
3078 -- We don't deal with anything except discrete types
3080 or else not Is_Discrete_Type (Typ)
3082 -- Ignore type for which an error has been posted, since range in
3083 -- this case may well be a bogosity deriving from the error. Also
3084 -- ignore if error posted on the reference node.
3086 or else Error_Posted (N) or else Error_Posted (Typ)
3087 then
3088 OK := False;
3089 return;
3090 end if;
3092 -- For all other cases, we can determine the range
3094 OK := True;
3096 -- If value is compile time known, then the possible range is the one
3097 -- value that we know this expression definitely has!
3099 if Compile_Time_Known_Value (N) then
3100 Lo := Expr_Value (N);
3101 Hi := Lo;
3102 return;
3103 end if;
3105 -- Return if already in the cache
3107 Cindex := Cache_Index (N mod Cache_Size);
3109 if Determine_Range_Cache_N (Cindex) = N
3110 and then
3111 Determine_Range_Cache_V (Cindex) = Assume_Valid
3112 then
3113 Lo := Determine_Range_Cache_Lo (Cindex);
3114 Hi := Determine_Range_Cache_Hi (Cindex);
3115 return;
3116 end if;
3118 -- Otherwise, start by finding the bounds of the type of the expression,
3119 -- the value cannot be outside this range (if it is, then we have an
3120 -- overflow situation, which is a separate check, we are talking here
3121 -- only about the expression value).
3123 -- First a check, never try to find the bounds of a generic type, since
3124 -- these bounds are always junk values, and it is only valid to look at
3125 -- the bounds in an instance.
3127 if Is_Generic_Type (Typ) then
3128 OK := False;
3129 return;
3130 end if;
3132 -- First step, change to use base type unless we know the value is valid
3134 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
3135 or else Assume_No_Invalid_Values
3136 or else Assume_Valid
3137 then
3138 null;
3139 else
3140 Typ := Underlying_Type (Base_Type (Typ));
3141 end if;
3143 -- We use the actual bound unless it is dynamic, in which case use the
3144 -- corresponding base type bound if possible. If we can't get a bound
3145 -- then we figure we can't determine the range (a peculiar case, that
3146 -- perhaps cannot happen, but there is no point in bombing in this
3147 -- optimization circuit.
3149 -- First the low bound
3151 Bound := Type_Low_Bound (Typ);
3153 if Compile_Time_Known_Value (Bound) then
3154 Lo := Expr_Value (Bound);
3156 elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
3157 Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
3159 else
3160 OK := False;
3161 return;
3162 end if;
3164 -- Now the high bound
3166 Bound := Type_High_Bound (Typ);
3168 -- We need the high bound of the base type later on, and this should
3169 -- always be compile time known. Again, it is not clear that this
3170 -- can ever be false, but no point in bombing.
3172 if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
3173 Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
3174 Hi := Hbound;
3176 else
3177 OK := False;
3178 return;
3179 end if;
3181 -- If we have a static subtype, then that may have a tighter bound so
3182 -- use the upper bound of the subtype instead in this case.
3184 if Compile_Time_Known_Value (Bound) then
3185 Hi := Expr_Value (Bound);
3186 end if;
3188 -- We may be able to refine this value in certain situations. If any
3189 -- refinement is possible, then Lor and Hir are set to possibly tighter
3190 -- bounds, and OK1 is set to True.
3192 case Nkind (N) is
3194 -- For unary plus, result is limited by range of operand
3196 when N_Op_Plus =>
3197 Determine_Range
3198 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
3200 -- For unary minus, determine range of operand, and negate it
3202 when N_Op_Minus =>
3203 Determine_Range
3204 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3206 if OK1 then
3207 Lor := -Hi_Right;
3208 Hir := -Lo_Right;
3209 end if;
3211 -- For binary addition, get range of each operand and do the
3212 -- addition to get the result range.
3214 when N_Op_Add =>
3215 if OK_Operands then
3216 Lor := Lo_Left + Lo_Right;
3217 Hir := Hi_Left + Hi_Right;
3218 end if;
3220 -- Division is tricky. The only case we consider is where the right
3221 -- operand is a positive constant, and in this case we simply divide
3222 -- the bounds of the left operand
3224 when N_Op_Divide =>
3225 if OK_Operands then
3226 if Lo_Right = Hi_Right
3227 and then Lo_Right > 0
3228 then
3229 Lor := Lo_Left / Lo_Right;
3230 Hir := Hi_Left / Lo_Right;
3232 else
3233 OK1 := False;
3234 end if;
3235 end if;
3237 -- For binary subtraction, get range of each operand and do the worst
3238 -- case subtraction to get the result range.
3240 when N_Op_Subtract =>
3241 if OK_Operands then
3242 Lor := Lo_Left - Hi_Right;
3243 Hir := Hi_Left - Lo_Right;
3244 end if;
3246 -- For MOD, if right operand is a positive constant, then result must
3247 -- be in the allowable range of mod results.
3249 when N_Op_Mod =>
3250 if OK_Operands then
3251 if Lo_Right = Hi_Right
3252 and then Lo_Right /= 0
3253 then
3254 if Lo_Right > 0 then
3255 Lor := Uint_0;
3256 Hir := Lo_Right - 1;
3258 else -- Lo_Right < 0
3259 Lor := Lo_Right + 1;
3260 Hir := Uint_0;
3261 end if;
3263 else
3264 OK1 := False;
3265 end if;
3266 end if;
3268 -- For REM, if right operand is a positive constant, then result must
3269 -- be in the allowable range of mod results.
3271 when N_Op_Rem =>
3272 if OK_Operands then
3273 if Lo_Right = Hi_Right
3274 and then Lo_Right /= 0
3275 then
3276 declare
3277 Dval : constant Uint := (abs Lo_Right) - 1;
3279 begin
3280 -- The sign of the result depends on the sign of the
3281 -- dividend (but not on the sign of the divisor, hence
3282 -- the abs operation above).
3284 if Lo_Left < 0 then
3285 Lor := -Dval;
3286 else
3287 Lor := Uint_0;
3288 end if;
3290 if Hi_Left < 0 then
3291 Hir := Uint_0;
3292 else
3293 Hir := Dval;
3294 end if;
3295 end;
3297 else
3298 OK1 := False;
3299 end if;
3300 end if;
3302 -- Attribute reference cases
3304 when N_Attribute_Reference =>
3305 case Attribute_Name (N) is
3307 -- For Pos/Val attributes, we can refine the range using the
3308 -- possible range of values of the attribute expression.
3310 when Name_Pos | Name_Val =>
3311 Determine_Range
3312 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
3314 -- For Length attribute, use the bounds of the corresponding
3315 -- index type to refine the range.
3317 when Name_Length =>
3318 declare
3319 Atyp : Entity_Id := Etype (Prefix (N));
3320 Inum : Nat;
3321 Indx : Node_Id;
3323 LL, LU : Uint;
3324 UL, UU : Uint;
3326 begin
3327 if Is_Access_Type (Atyp) then
3328 Atyp := Designated_Type (Atyp);
3329 end if;
3331 -- For string literal, we know exact value
3333 if Ekind (Atyp) = E_String_Literal_Subtype then
3334 OK := True;
3335 Lo := String_Literal_Length (Atyp);
3336 Hi := String_Literal_Length (Atyp);
3337 return;
3338 end if;
3340 -- Otherwise check for expression given
3342 if No (Expressions (N)) then
3343 Inum := 1;
3344 else
3345 Inum :=
3346 UI_To_Int (Expr_Value (First (Expressions (N))));
3347 end if;
3349 Indx := First_Index (Atyp);
3350 for J in 2 .. Inum loop
3351 Indx := Next_Index (Indx);
3352 end loop;
3354 -- If the index type is a formal type or derived from
3355 -- one, the bounds are not static.
3357 if Is_Generic_Type (Root_Type (Etype (Indx))) then
3358 OK := False;
3359 return;
3360 end if;
3362 Determine_Range
3363 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
3364 Assume_Valid);
3366 if OK1 then
3367 Determine_Range
3368 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
3369 Assume_Valid);
3371 if OK1 then
3373 -- The maximum value for Length is the biggest
3374 -- possible gap between the values of the bounds.
3375 -- But of course, this value cannot be negative.
3377 Hir := UI_Max (Uint_0, UU - LL + 1);
3379 -- For constrained arrays, the minimum value for
3380 -- Length is taken from the actual value of the
3381 -- bounds, since the index will be exactly of this
3382 -- subtype.
3384 if Is_Constrained (Atyp) then
3385 Lor := UI_Max (Uint_0, UL - LU + 1);
3387 -- For an unconstrained array, the minimum value
3388 -- for length is always zero.
3390 else
3391 Lor := Uint_0;
3392 end if;
3393 end if;
3394 end if;
3395 end;
3397 -- No special handling for other attributes
3398 -- Probably more opportunities exist here???
3400 when others =>
3401 OK1 := False;
3403 end case;
3405 -- For type conversion from one discrete type to another, we can
3406 -- refine the range using the converted value.
3408 when N_Type_Conversion =>
3409 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
3411 -- Nothing special to do for all other expression kinds
3413 when others =>
3414 OK1 := False;
3415 Lor := No_Uint;
3416 Hir := No_Uint;
3417 end case;
3419 -- At this stage, if OK1 is true, then we know that the actual result of
3420 -- the computed expression is in the range Lor .. Hir. We can use this
3421 -- to restrict the possible range of results.
3423 if OK1 then
3425 -- If the refined value of the low bound is greater than the type
3426 -- high bound, then reset it to the more restrictive value. However,
3427 -- we do NOT do this for the case of a modular type where the
3428 -- possible upper bound on the value is above the base type high
3429 -- bound, because that means the result could wrap.
3431 if Lor > Lo
3432 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
3433 then
3434 Lo := Lor;
3435 end if;
3437 -- Similarly, if the refined value of the high bound is less than the
3438 -- value so far, then reset it to the more restrictive value. Again,
3439 -- we do not do this if the refined low bound is negative for a
3440 -- modular type, since this would wrap.
3442 if Hir < Hi
3443 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
3444 then
3445 Hi := Hir;
3446 end if;
3447 end if;
3449 -- Set cache entry for future call and we are all done
3451 Determine_Range_Cache_N (Cindex) := N;
3452 Determine_Range_Cache_V (Cindex) := Assume_Valid;
3453 Determine_Range_Cache_Lo (Cindex) := Lo;
3454 Determine_Range_Cache_Hi (Cindex) := Hi;
3455 return;
3457 -- If any exception occurs, it means that we have some bug in the compiler,
3458 -- possibly triggered by a previous error, or by some unforeseen peculiar
3459 -- occurrence. However, this is only an optimization attempt, so there is
3460 -- really no point in crashing the compiler. Instead we just decide, too
3461 -- bad, we can't figure out a range in this case after all.
3463 exception
3464 when others =>
3466 -- Debug flag K disables this behavior (useful for debugging)
3468 if Debug_Flag_K then
3469 raise;
3470 else
3471 OK := False;
3472 Lo := No_Uint;
3473 Hi := No_Uint;
3474 return;
3475 end if;
3476 end Determine_Range;
3478 ------------------------------------
3479 -- Discriminant_Checks_Suppressed --
3480 ------------------------------------
3482 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3483 begin
3484 if Present (E) then
3485 if Is_Unchecked_Union (E) then
3486 return True;
3487 elsif Checks_May_Be_Suppressed (E) then
3488 return Is_Check_Suppressed (E, Discriminant_Check);
3489 end if;
3490 end if;
3492 return Scope_Suppress (Discriminant_Check);
3493 end Discriminant_Checks_Suppressed;
3495 --------------------------------
3496 -- Division_Checks_Suppressed --
3497 --------------------------------
3499 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3500 begin
3501 if Present (E) and then Checks_May_Be_Suppressed (E) then
3502 return Is_Check_Suppressed (E, Division_Check);
3503 else
3504 return Scope_Suppress (Division_Check);
3505 end if;
3506 end Division_Checks_Suppressed;
3508 -----------------------------------
3509 -- Elaboration_Checks_Suppressed --
3510 -----------------------------------
3512 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3513 begin
3514 -- The complication in this routine is that if we are in the dynamic
3515 -- model of elaboration, we also check All_Checks, since All_Checks
3516 -- does not set Elaboration_Check explicitly.
3518 if Present (E) then
3519 if Kill_Elaboration_Checks (E) then
3520 return True;
3522 elsif Checks_May_Be_Suppressed (E) then
3523 if Is_Check_Suppressed (E, Elaboration_Check) then
3524 return True;
3525 elsif Dynamic_Elaboration_Checks then
3526 return Is_Check_Suppressed (E, All_Checks);
3527 else
3528 return False;
3529 end if;
3530 end if;
3531 end if;
3533 if Scope_Suppress (Elaboration_Check) then
3534 return True;
3535 elsif Dynamic_Elaboration_Checks then
3536 return Scope_Suppress (All_Checks);
3537 else
3538 return False;
3539 end if;
3540 end Elaboration_Checks_Suppressed;
3542 ---------------------------
3543 -- Enable_Overflow_Check --
3544 ---------------------------
3546 procedure Enable_Overflow_Check (N : Node_Id) is
3547 Typ : constant Entity_Id := Base_Type (Etype (N));
3548 Chk : Nat;
3549 OK : Boolean;
3550 Ent : Entity_Id;
3551 Ofs : Uint;
3552 Lo : Uint;
3553 Hi : Uint;
3555 begin
3556 if Debug_Flag_CC then
3557 w ("Enable_Overflow_Check for node ", Int (N));
3558 Write_Str (" Source location = ");
3559 wl (Sloc (N));
3560 pg (Union_Id (N));
3561 end if;
3563 -- No check if overflow checks suppressed for type of node
3565 if Present (Etype (N))
3566 and then Overflow_Checks_Suppressed (Etype (N))
3567 then
3568 return;
3570 -- Nothing to do for unsigned integer types, which do not overflow
3572 elsif Is_Modular_Integer_Type (Typ) then
3573 return;
3575 -- Nothing to do if the range of the result is known OK. We skip this
3576 -- for conversions, since the caller already did the check, and in any
3577 -- case the condition for deleting the check for a type conversion is
3578 -- different.
3580 elsif Nkind (N) /= N_Type_Conversion then
3581 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
3583 -- Note in the test below that we assume that the range is not OK
3584 -- if a bound of the range is equal to that of the type. That's not
3585 -- quite accurate but we do this for the following reasons:
3587 -- a) The way that Determine_Range works, it will typically report
3588 -- the bounds of the value as being equal to the bounds of the
3589 -- type, because it either can't tell anything more precise, or
3590 -- does not think it is worth the effort to be more precise.
3592 -- b) It is very unusual to have a situation in which this would
3593 -- generate an unnecessary overflow check (an example would be
3594 -- a subtype with a range 0 .. Integer'Last - 1 to which the
3595 -- literal value one is added).
3597 -- c) The alternative is a lot of special casing in this routine
3598 -- which would partially duplicate Determine_Range processing.
3600 if OK
3601 and then Lo > Expr_Value (Type_Low_Bound (Typ))
3602 and then Hi < Expr_Value (Type_High_Bound (Typ))
3603 then
3604 if Debug_Flag_CC then
3605 w ("No overflow check required");
3606 end if;
3608 return;
3609 end if;
3610 end if;
3612 -- If not in optimizing mode, set flag and we are done. We are also done
3613 -- (and just set the flag) if the type is not a discrete type, since it
3614 -- is not worth the effort to eliminate checks for other than discrete
3615 -- types. In addition, we take this same path if we have stored the
3616 -- maximum number of checks possible already (a very unlikely situation,
3617 -- but we do not want to blow up!)
3619 if Optimization_Level = 0
3620 or else not Is_Discrete_Type (Etype (N))
3621 or else Num_Saved_Checks = Saved_Checks'Last
3622 then
3623 Activate_Overflow_Check (N);
3625 if Debug_Flag_CC then
3626 w ("Optimization off");
3627 end if;
3629 return;
3630 end if;
3632 -- Otherwise evaluate and check the expression
3634 Find_Check
3635 (Expr => N,
3636 Check_Type => 'O',
3637 Target_Type => Empty,
3638 Entry_OK => OK,
3639 Check_Num => Chk,
3640 Ent => Ent,
3641 Ofs => Ofs);
3643 if Debug_Flag_CC then
3644 w ("Called Find_Check");
3645 w (" OK = ", OK);
3647 if OK then
3648 w (" Check_Num = ", Chk);
3649 w (" Ent = ", Int (Ent));
3650 Write_Str (" Ofs = ");
3651 pid (Ofs);
3652 end if;
3653 end if;
3655 -- If check is not of form to optimize, then set flag and we are done
3657 if not OK then
3658 Activate_Overflow_Check (N);
3659 return;
3660 end if;
3662 -- If check is already performed, then return without setting flag
3664 if Chk /= 0 then
3665 if Debug_Flag_CC then
3666 w ("Check suppressed!");
3667 end if;
3669 return;
3670 end if;
3672 -- Here we will make a new entry for the new check
3674 Activate_Overflow_Check (N);
3675 Num_Saved_Checks := Num_Saved_Checks + 1;
3676 Saved_Checks (Num_Saved_Checks) :=
3677 (Killed => False,
3678 Entity => Ent,
3679 Offset => Ofs,
3680 Check_Type => 'O',
3681 Target_Type => Empty);
3683 if Debug_Flag_CC then
3684 w ("Make new entry, check number = ", Num_Saved_Checks);
3685 w (" Entity = ", Int (Ent));
3686 Write_Str (" Offset = ");
3687 pid (Ofs);
3688 w (" Check_Type = O");
3689 w (" Target_Type = Empty");
3690 end if;
3692 -- If we get an exception, then something went wrong, probably because of
3693 -- an error in the structure of the tree due to an incorrect program. Or it
3694 -- may be a bug in the optimization circuit. In either case the safest
3695 -- thing is simply to set the check flag unconditionally.
3697 exception
3698 when others =>
3699 Activate_Overflow_Check (N);
3701 if Debug_Flag_CC then
3702 w (" exception occurred, overflow flag set");
3703 end if;
3705 return;
3706 end Enable_Overflow_Check;
3708 ------------------------
3709 -- Enable_Range_Check --
3710 ------------------------
3712 procedure Enable_Range_Check (N : Node_Id) is
3713 Chk : Nat;
3714 OK : Boolean;
3715 Ent : Entity_Id;
3716 Ofs : Uint;
3717 Ttyp : Entity_Id;
3718 P : Node_Id;
3720 begin
3721 -- Return if unchecked type conversion with range check killed. In this
3722 -- case we never set the flag (that's what Kill_Range_Check is about!)
3724 if Nkind (N) = N_Unchecked_Type_Conversion
3725 and then Kill_Range_Check (N)
3726 then
3727 return;
3728 end if;
3730 -- Check for various cases where we should suppress the range check
3732 -- No check if range checks suppressed for type of node
3734 if Present (Etype (N))
3735 and then Range_Checks_Suppressed (Etype (N))
3736 then
3737 return;
3739 -- No check if node is an entity name, and range checks are suppressed
3740 -- for this entity, or for the type of this entity.
3742 elsif Is_Entity_Name (N)
3743 and then (Range_Checks_Suppressed (Entity (N))
3744 or else Range_Checks_Suppressed (Etype (Entity (N))))
3745 then
3746 return;
3748 -- No checks if index of array, and index checks are suppressed for
3749 -- the array object or the type of the array.
3751 elsif Nkind (Parent (N)) = N_Indexed_Component then
3752 declare
3753 Pref : constant Node_Id := Prefix (Parent (N));
3754 begin
3755 if Is_Entity_Name (Pref)
3756 and then Index_Checks_Suppressed (Entity (Pref))
3757 then
3758 return;
3759 elsif Index_Checks_Suppressed (Etype (Pref)) then
3760 return;
3761 end if;
3762 end;
3763 end if;
3765 -- Debug trace output
3767 if Debug_Flag_CC then
3768 w ("Enable_Range_Check for node ", Int (N));
3769 Write_Str (" Source location = ");
3770 wl (Sloc (N));
3771 pg (Union_Id (N));
3772 end if;
3774 -- If not in optimizing mode, set flag and we are done. We are also done
3775 -- (and just set the flag) if the type is not a discrete type, since it
3776 -- is not worth the effort to eliminate checks for other than discrete
3777 -- types. In addition, we take this same path if we have stored the
3778 -- maximum number of checks possible already (a very unlikely situation,
3779 -- but we do not want to blow up!)
3781 if Optimization_Level = 0
3782 or else No (Etype (N))
3783 or else not Is_Discrete_Type (Etype (N))
3784 or else Num_Saved_Checks = Saved_Checks'Last
3785 then
3786 Activate_Range_Check (N);
3788 if Debug_Flag_CC then
3789 w ("Optimization off");
3790 end if;
3792 return;
3793 end if;
3795 -- Otherwise find out the target type
3797 P := Parent (N);
3799 -- For assignment, use left side subtype
3801 if Nkind (P) = N_Assignment_Statement
3802 and then Expression (P) = N
3803 then
3804 Ttyp := Etype (Name (P));
3806 -- For indexed component, use subscript subtype
3808 elsif Nkind (P) = N_Indexed_Component then
3809 declare
3810 Atyp : Entity_Id;
3811 Indx : Node_Id;
3812 Subs : Node_Id;
3814 begin
3815 Atyp := Etype (Prefix (P));
3817 if Is_Access_Type (Atyp) then
3818 Atyp := Designated_Type (Atyp);
3820 -- If the prefix is an access to an unconstrained array,
3821 -- perform check unconditionally: it depends on the bounds of
3822 -- an object and we cannot currently recognize whether the test
3823 -- may be redundant.
3825 if not Is_Constrained (Atyp) then
3826 Activate_Range_Check (N);
3827 return;
3828 end if;
3830 -- Ditto if the prefix is an explicit dereference whose designated
3831 -- type is unconstrained.
3833 elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3834 and then not Is_Constrained (Atyp)
3835 then
3836 Activate_Range_Check (N);
3837 return;
3838 end if;
3840 Indx := First_Index (Atyp);
3841 Subs := First (Expressions (P));
3842 loop
3843 if Subs = N then
3844 Ttyp := Etype (Indx);
3845 exit;
3846 end if;
3848 Next_Index (Indx);
3849 Next (Subs);
3850 end loop;
3851 end;
3853 -- For now, ignore all other cases, they are not so interesting
3855 else
3856 if Debug_Flag_CC then
3857 w (" target type not found, flag set");
3858 end if;
3860 Activate_Range_Check (N);
3861 return;
3862 end if;
3864 -- Evaluate and check the expression
3866 Find_Check
3867 (Expr => N,
3868 Check_Type => 'R',
3869 Target_Type => Ttyp,
3870 Entry_OK => OK,
3871 Check_Num => Chk,
3872 Ent => Ent,
3873 Ofs => Ofs);
3875 if Debug_Flag_CC then
3876 w ("Called Find_Check");
3877 w ("Target_Typ = ", Int (Ttyp));
3878 w (" OK = ", OK);
3880 if OK then
3881 w (" Check_Num = ", Chk);
3882 w (" Ent = ", Int (Ent));
3883 Write_Str (" Ofs = ");
3884 pid (Ofs);
3885 end if;
3886 end if;
3888 -- If check is not of form to optimize, then set flag and we are done
3890 if not OK then
3891 if Debug_Flag_CC then
3892 w (" expression not of optimizable type, flag set");
3893 end if;
3895 Activate_Range_Check (N);
3896 return;
3897 end if;
3899 -- If check is already performed, then return without setting flag
3901 if Chk /= 0 then
3902 if Debug_Flag_CC then
3903 w ("Check suppressed!");
3904 end if;
3906 return;
3907 end if;
3909 -- Here we will make a new entry for the new check
3911 Activate_Range_Check (N);
3912 Num_Saved_Checks := Num_Saved_Checks + 1;
3913 Saved_Checks (Num_Saved_Checks) :=
3914 (Killed => False,
3915 Entity => Ent,
3916 Offset => Ofs,
3917 Check_Type => 'R',
3918 Target_Type => Ttyp);
3920 if Debug_Flag_CC then
3921 w ("Make new entry, check number = ", Num_Saved_Checks);
3922 w (" Entity = ", Int (Ent));
3923 Write_Str (" Offset = ");
3924 pid (Ofs);
3925 w (" Check_Type = R");
3926 w (" Target_Type = ", Int (Ttyp));
3927 pg (Union_Id (Ttyp));
3928 end if;
3930 -- If we get an exception, then something went wrong, probably because of
3931 -- an error in the structure of the tree due to an incorrect program. Or
3932 -- it may be a bug in the optimization circuit. In either case the safest
3933 -- thing is simply to set the check flag unconditionally.
3935 exception
3936 when others =>
3937 Activate_Range_Check (N);
3939 if Debug_Flag_CC then
3940 w (" exception occurred, range flag set");
3941 end if;
3943 return;
3944 end Enable_Range_Check;
3946 ------------------
3947 -- Ensure_Valid --
3948 ------------------
3950 procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3951 Typ : constant Entity_Id := Etype (Expr);
3953 begin
3954 -- Ignore call if we are not doing any validity checking
3956 if not Validity_Checks_On then
3957 return;
3959 -- Ignore call if range or validity checks suppressed on entity or type
3961 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3962 return;
3964 -- No check required if expression is from the expander, we assume the
3965 -- expander will generate whatever checks are needed. Note that this is
3966 -- not just an optimization, it avoids infinite recursions!
3968 -- Unchecked conversions must be checked, unless they are initialized
3969 -- scalar values, as in a component assignment in an init proc.
3971 -- In addition, we force a check if Force_Validity_Checks is set
3973 elsif not Comes_From_Source (Expr)
3974 and then not Force_Validity_Checks
3975 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
3976 or else Kill_Range_Check (Expr))
3977 then
3978 return;
3980 -- No check required if expression is known to have valid value
3982 elsif Expr_Known_Valid (Expr) then
3983 return;
3985 -- Ignore case of enumeration with holes where the flag is set not to
3986 -- worry about holes, since no special validity check is needed
3988 elsif Is_Enumeration_Type (Typ)
3989 and then Has_Non_Standard_Rep (Typ)
3990 and then Holes_OK
3991 then
3992 return;
3994 -- No check required on the left-hand side of an assignment
3996 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
3997 and then Expr = Name (Parent (Expr))
3998 then
3999 return;
4001 -- No check on a univeral real constant. The context will eventually
4002 -- convert it to a machine number for some target type, or report an
4003 -- illegality.
4005 elsif Nkind (Expr) = N_Real_Literal
4006 and then Etype (Expr) = Universal_Real
4007 then
4008 return;
4010 -- If the expression denotes a component of a packed boolean arrray,
4011 -- no possible check applies. We ignore the old ACATS chestnuts that
4012 -- involve Boolean range True..True.
4014 -- Note: validity checks are generated for expressions that yield a
4015 -- scalar type, when it is possible to create a value that is outside of
4016 -- the type. If this is a one-bit boolean no such value exists. This is
4017 -- an optimization, and it also prevents compiler blowing up during the
4018 -- elaboration of improperly expanded packed array references.
4020 elsif Nkind (Expr) = N_Indexed_Component
4021 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
4022 and then Root_Type (Etype (Expr)) = Standard_Boolean
4023 then
4024 return;
4026 -- An annoying special case. If this is an out parameter of a scalar
4027 -- type, then the value is not going to be accessed, therefore it is
4028 -- inappropriate to do any validity check at the call site.
4030 else
4031 -- Only need to worry about scalar types
4033 if Is_Scalar_Type (Typ) then
4034 declare
4035 P : Node_Id;
4036 N : Node_Id;
4037 E : Entity_Id;
4038 F : Entity_Id;
4039 A : Node_Id;
4040 L : List_Id;
4042 begin
4043 -- Find actual argument (which may be a parameter association)
4044 -- and the parent of the actual argument (the call statement)
4046 N := Expr;
4047 P := Parent (Expr);
4049 if Nkind (P) = N_Parameter_Association then
4050 N := P;
4051 P := Parent (N);
4052 end if;
4054 -- Only need to worry if we are argument of a procedure call
4055 -- since functions don't have out parameters. If this is an
4056 -- indirect or dispatching call, get signature from the
4057 -- subprogram type.
4059 if Nkind (P) = N_Procedure_Call_Statement then
4060 L := Parameter_Associations (P);
4062 if Is_Entity_Name (Name (P)) then
4063 E := Entity (Name (P));
4064 else
4065 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
4066 E := Etype (Name (P));
4067 end if;
4069 -- Only need to worry if there are indeed actuals, and if
4070 -- this could be a procedure call, otherwise we cannot get a
4071 -- match (either we are not an argument, or the mode of the
4072 -- formal is not OUT). This test also filters out the
4073 -- generic case.
4075 if Is_Non_Empty_List (L)
4076 and then Is_Subprogram (E)
4077 then
4078 -- This is the loop through parameters, looking for an
4079 -- OUT parameter for which we are the argument.
4081 F := First_Formal (E);
4082 A := First (L);
4083 while Present (F) loop
4084 if Ekind (F) = E_Out_Parameter and then A = N then
4085 return;
4086 end if;
4088 Next_Formal (F);
4089 Next (A);
4090 end loop;
4091 end if;
4092 end if;
4093 end;
4094 end if;
4095 end if;
4097 -- If we fall through, a validity check is required
4099 Insert_Valid_Check (Expr);
4101 if Is_Entity_Name (Expr)
4102 and then Safe_To_Capture_Value (Expr, Entity (Expr))
4103 then
4104 Set_Is_Known_Valid (Entity (Expr));
4105 end if;
4106 end Ensure_Valid;
4108 ----------------------
4109 -- Expr_Known_Valid --
4110 ----------------------
4112 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
4113 Typ : constant Entity_Id := Etype (Expr);
4115 begin
4116 -- Non-scalar types are always considered valid, since they never give
4117 -- rise to the issues of erroneous or bounded error behavior that are
4118 -- the concern. In formal reference manual terms the notion of validity
4119 -- only applies to scalar types. Note that even when packed arrays are
4120 -- represented using modular types, they are still arrays semantically,
4121 -- so they are also always valid (in particular, the unused bits can be
4122 -- random rubbish without affecting the validity of the array value).
4124 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
4125 return True;
4127 -- If no validity checking, then everything is considered valid
4129 elsif not Validity_Checks_On then
4130 return True;
4132 -- Floating-point types are considered valid unless floating-point
4133 -- validity checks have been specifically turned on.
4135 elsif Is_Floating_Point_Type (Typ)
4136 and then not Validity_Check_Floating_Point
4137 then
4138 return True;
4140 -- If the expression is the value of an object that is known to be
4141 -- valid, then clearly the expression value itself is valid.
4143 elsif Is_Entity_Name (Expr)
4144 and then Is_Known_Valid (Entity (Expr))
4145 then
4146 return True;
4148 -- References to discriminants are always considered valid. The value
4149 -- of a discriminant gets checked when the object is built. Within the
4150 -- record, we consider it valid, and it is important to do so, since
4151 -- otherwise we can try to generate bogus validity checks which
4152 -- reference discriminants out of scope. Discriminants of concurrent
4153 -- types are excluded for the same reason.
4155 elsif Is_Entity_Name (Expr)
4156 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
4157 then
4158 return True;
4160 -- If the type is one for which all values are known valid, then we are
4161 -- sure that the value is valid except in the slightly odd case where
4162 -- the expression is a reference to a variable whose size has been
4163 -- explicitly set to a value greater than the object size.
4165 elsif Is_Known_Valid (Typ) then
4166 if Is_Entity_Name (Expr)
4167 and then Ekind (Entity (Expr)) = E_Variable
4168 and then Esize (Entity (Expr)) > Esize (Typ)
4169 then
4170 return False;
4171 else
4172 return True;
4173 end if;
4175 -- Integer and character literals always have valid values, where
4176 -- appropriate these will be range checked in any case.
4178 elsif Nkind (Expr) = N_Integer_Literal
4179 or else
4180 Nkind (Expr) = N_Character_Literal
4181 then
4182 return True;
4184 -- If we have a type conversion or a qualification of a known valid
4185 -- value, then the result will always be valid.
4187 elsif Nkind (Expr) = N_Type_Conversion
4188 or else
4189 Nkind (Expr) = N_Qualified_Expression
4190 then
4191 return Expr_Known_Valid (Expression (Expr));
4193 -- The result of any operator is always considered valid, since we
4194 -- assume the necessary checks are done by the operator. For operators
4195 -- on floating-point operations, we must also check when the operation
4196 -- is the right-hand side of an assignment, or is an actual in a call.
4198 elsif Nkind (Expr) in N_Op then
4199 if Is_Floating_Point_Type (Typ)
4200 and then Validity_Check_Floating_Point
4201 and then
4202 (Nkind (Parent (Expr)) = N_Assignment_Statement
4203 or else Nkind (Parent (Expr)) = N_Function_Call
4204 or else Nkind (Parent (Expr)) = N_Parameter_Association)
4205 then
4206 return False;
4207 else
4208 return True;
4209 end if;
4211 -- The result of a membership test is always valid, since it is true or
4212 -- false, there are no other possibilities.
4214 elsif Nkind (Expr) in N_Membership_Test then
4215 return True;
4217 -- For all other cases, we do not know the expression is valid
4219 else
4220 return False;
4221 end if;
4222 end Expr_Known_Valid;
4224 ----------------
4225 -- Find_Check --
4226 ----------------
4228 procedure Find_Check
4229 (Expr : Node_Id;
4230 Check_Type : Character;
4231 Target_Type : Entity_Id;
4232 Entry_OK : out Boolean;
4233 Check_Num : out Nat;
4234 Ent : out Entity_Id;
4235 Ofs : out Uint)
4237 function Within_Range_Of
4238 (Target_Type : Entity_Id;
4239 Check_Type : Entity_Id) return Boolean;
4240 -- Given a requirement for checking a range against Target_Type, and
4241 -- and a range Check_Type against which a check has already been made,
4242 -- determines if the check against check type is sufficient to ensure
4243 -- that no check against Target_Type is required.
4245 ---------------------
4246 -- Within_Range_Of --
4247 ---------------------
4249 function Within_Range_Of
4250 (Target_Type : Entity_Id;
4251 Check_Type : Entity_Id) return Boolean
4253 begin
4254 if Target_Type = Check_Type then
4255 return True;
4257 else
4258 declare
4259 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
4260 Thi : constant Node_Id := Type_High_Bound (Target_Type);
4261 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
4262 Chi : constant Node_Id := Type_High_Bound (Check_Type);
4264 begin
4265 if (Tlo = Clo
4266 or else (Compile_Time_Known_Value (Tlo)
4267 and then
4268 Compile_Time_Known_Value (Clo)
4269 and then
4270 Expr_Value (Clo) >= Expr_Value (Tlo)))
4271 and then
4272 (Thi = Chi
4273 or else (Compile_Time_Known_Value (Thi)
4274 and then
4275 Compile_Time_Known_Value (Chi)
4276 and then
4277 Expr_Value (Chi) <= Expr_Value (Clo)))
4278 then
4279 return True;
4280 else
4281 return False;
4282 end if;
4283 end;
4284 end if;
4285 end Within_Range_Of;
4287 -- Start of processing for Find_Check
4289 begin
4290 -- Establish default, in case no entry is found
4292 Check_Num := 0;
4294 -- Case of expression is simple entity reference
4296 if Is_Entity_Name (Expr) then
4297 Ent := Entity (Expr);
4298 Ofs := Uint_0;
4300 -- Case of expression is entity + known constant
4302 elsif Nkind (Expr) = N_Op_Add
4303 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4304 and then Is_Entity_Name (Left_Opnd (Expr))
4305 then
4306 Ent := Entity (Left_Opnd (Expr));
4307 Ofs := Expr_Value (Right_Opnd (Expr));
4309 -- Case of expression is entity - known constant
4311 elsif Nkind (Expr) = N_Op_Subtract
4312 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4313 and then Is_Entity_Name (Left_Opnd (Expr))
4314 then
4315 Ent := Entity (Left_Opnd (Expr));
4316 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4318 -- Any other expression is not of the right form
4320 else
4321 Ent := Empty;
4322 Ofs := Uint_0;
4323 Entry_OK := False;
4324 return;
4325 end if;
4327 -- Come here with expression of appropriate form, check if entity is an
4328 -- appropriate one for our purposes.
4330 if (Ekind (Ent) = E_Variable
4331 or else Is_Constant_Object (Ent))
4332 and then not Is_Library_Level_Entity (Ent)
4333 then
4334 Entry_OK := True;
4335 else
4336 Entry_OK := False;
4337 return;
4338 end if;
4340 -- See if there is matching check already
4342 for J in reverse 1 .. Num_Saved_Checks loop
4343 declare
4344 SC : Saved_Check renames Saved_Checks (J);
4346 begin
4347 if SC.Killed = False
4348 and then SC.Entity = Ent
4349 and then SC.Offset = Ofs
4350 and then SC.Check_Type = Check_Type
4351 and then Within_Range_Of (Target_Type, SC.Target_Type)
4352 then
4353 Check_Num := J;
4354 return;
4355 end if;
4356 end;
4357 end loop;
4359 -- If we fall through entry was not found
4361 return;
4362 end Find_Check;
4364 ---------------------------------
4365 -- Generate_Discriminant_Check --
4366 ---------------------------------
4368 -- Note: the code for this procedure is derived from the
4369 -- Emit_Discriminant_Check Routine in trans.c.
4371 procedure Generate_Discriminant_Check (N : Node_Id) is
4372 Loc : constant Source_Ptr := Sloc (N);
4373 Pref : constant Node_Id := Prefix (N);
4374 Sel : constant Node_Id := Selector_Name (N);
4376 Orig_Comp : constant Entity_Id :=
4377 Original_Record_Component (Entity (Sel));
4378 -- The original component to be checked
4380 Discr_Fct : constant Entity_Id :=
4381 Discriminant_Checking_Func (Orig_Comp);
4382 -- The discriminant checking function
4384 Discr : Entity_Id;
4385 -- One discriminant to be checked in the type
4387 Real_Discr : Entity_Id;
4388 -- Actual discriminant in the call
4390 Pref_Type : Entity_Id;
4391 -- Type of relevant prefix (ignoring private/access stuff)
4393 Args : List_Id;
4394 -- List of arguments for function call
4396 Formal : Entity_Id;
4397 -- Keep track of the formal corresponding to the actual we build for
4398 -- each discriminant, in order to be able to perform the necessary type
4399 -- conversions.
4401 Scomp : Node_Id;
4402 -- Selected component reference for checking function argument
4404 begin
4405 Pref_Type := Etype (Pref);
4407 -- Force evaluation of the prefix, so that it does not get evaluated
4408 -- twice (once for the check, once for the actual reference). Such a
4409 -- double evaluation is always a potential source of inefficiency,
4410 -- and is functionally incorrect in the volatile case, or when the
4411 -- prefix may have side-effects. An entity or a component of an
4412 -- entity requires no evaluation.
4414 if Is_Entity_Name (Pref) then
4415 if Treat_As_Volatile (Entity (Pref)) then
4416 Force_Evaluation (Pref, Name_Req => True);
4417 end if;
4419 elsif Treat_As_Volatile (Etype (Pref)) then
4420 Force_Evaluation (Pref, Name_Req => True);
4422 elsif Nkind (Pref) = N_Selected_Component
4423 and then Is_Entity_Name (Prefix (Pref))
4424 then
4425 null;
4427 else
4428 Force_Evaluation (Pref, Name_Req => True);
4429 end if;
4431 -- For a tagged type, use the scope of the original component to
4432 -- obtain the type, because ???
4434 if Is_Tagged_Type (Scope (Orig_Comp)) then
4435 Pref_Type := Scope (Orig_Comp);
4437 -- For an untagged derived type, use the discriminants of the parent
4438 -- which have been renamed in the derivation, possibly by a one-to-many
4439 -- discriminant constraint. For non-tagged type, initially get the Etype
4440 -- of the prefix
4442 else
4443 if Is_Derived_Type (Pref_Type)
4444 and then Number_Discriminants (Pref_Type) /=
4445 Number_Discriminants (Etype (Base_Type (Pref_Type)))
4446 then
4447 Pref_Type := Etype (Base_Type (Pref_Type));
4448 end if;
4449 end if;
4451 -- We definitely should have a checking function, This routine should
4452 -- not be called if no discriminant checking function is present.
4454 pragma Assert (Present (Discr_Fct));
4456 -- Create the list of the actual parameters for the call. This list
4457 -- is the list of the discriminant fields of the record expression to
4458 -- be discriminant checked.
4460 Args := New_List;
4461 Formal := First_Formal (Discr_Fct);
4462 Discr := First_Discriminant (Pref_Type);
4463 while Present (Discr) loop
4465 -- If we have a corresponding discriminant field, and a parent
4466 -- subtype is present, then we want to use the corresponding
4467 -- discriminant since this is the one with the useful value.
4469 if Present (Corresponding_Discriminant (Discr))
4470 and then Ekind (Pref_Type) = E_Record_Type
4471 and then Present (Parent_Subtype (Pref_Type))
4472 then
4473 Real_Discr := Corresponding_Discriminant (Discr);
4474 else
4475 Real_Discr := Discr;
4476 end if;
4478 -- Construct the reference to the discriminant
4480 Scomp :=
4481 Make_Selected_Component (Loc,
4482 Prefix =>
4483 Unchecked_Convert_To (Pref_Type,
4484 Duplicate_Subexpr (Pref)),
4485 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4487 -- Manually analyze and resolve this selected component. We really
4488 -- want it just as it appears above, and do not want the expander
4489 -- playing discriminal games etc with this reference. Then we append
4490 -- the argument to the list we are gathering.
4492 Set_Etype (Scomp, Etype (Real_Discr));
4493 Set_Analyzed (Scomp, True);
4494 Append_To (Args, Convert_To (Etype (Formal), Scomp));
4496 Next_Formal_With_Extras (Formal);
4497 Next_Discriminant (Discr);
4498 end loop;
4500 -- Now build and insert the call
4502 Insert_Action (N,
4503 Make_Raise_Constraint_Error (Loc,
4504 Condition =>
4505 Make_Function_Call (Loc,
4506 Name => New_Occurrence_Of (Discr_Fct, Loc),
4507 Parameter_Associations => Args),
4508 Reason => CE_Discriminant_Check_Failed));
4509 end Generate_Discriminant_Check;
4511 ---------------------------
4512 -- Generate_Index_Checks --
4513 ---------------------------
4515 procedure Generate_Index_Checks (N : Node_Id) is
4516 Loc : constant Source_Ptr := Sloc (N);
4517 A : constant Node_Id := Prefix (N);
4518 Sub : Node_Id;
4519 Ind : Nat;
4520 Num : List_Id;
4522 begin
4523 -- Ignore call if index checks suppressed for array object or type
4525 if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4526 or else Index_Checks_Suppressed (Etype (A))
4527 then
4528 return;
4529 end if;
4531 -- Generate the checks
4533 Sub := First (Expressions (N));
4534 Ind := 1;
4535 while Present (Sub) loop
4536 if Do_Range_Check (Sub) then
4537 Set_Do_Range_Check (Sub, False);
4539 -- Force evaluation except for the case of a simple name of a
4540 -- non-volatile entity.
4542 if not Is_Entity_Name (Sub)
4543 or else Treat_As_Volatile (Entity (Sub))
4544 then
4545 Force_Evaluation (Sub);
4546 end if;
4548 -- Generate a raise of constraint error with the appropriate
4549 -- reason and a condition of the form:
4551 -- Base_Type(Sub) not in array'range (subscript)
4553 -- Note that the reason we generate the conversion to the base
4554 -- type here is that we definitely want the range check to take
4555 -- place, even if it looks like the subtype is OK. Optimization
4556 -- considerations that allow us to omit the check have already
4557 -- been taken into account in the setting of the Do_Range_Check
4558 -- flag earlier on.
4560 if Ind = 1 then
4561 Num := No_List;
4562 else
4563 Num := New_List (Make_Integer_Literal (Loc, Ind));
4564 end if;
4566 Insert_Action (N,
4567 Make_Raise_Constraint_Error (Loc,
4568 Condition =>
4569 Make_Not_In (Loc,
4570 Left_Opnd =>
4571 Convert_To (Base_Type (Etype (Sub)),
4572 Duplicate_Subexpr_Move_Checks (Sub)),
4573 Right_Opnd =>
4574 Make_Attribute_Reference (Loc,
4575 Prefix =>
4576 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
4577 Attribute_Name => Name_Range,
4578 Expressions => Num)),
4579 Reason => CE_Index_Check_Failed));
4580 end if;
4582 Ind := Ind + 1;
4583 Next (Sub);
4584 end loop;
4585 end Generate_Index_Checks;
4587 --------------------------
4588 -- Generate_Range_Check --
4589 --------------------------
4591 procedure Generate_Range_Check
4592 (N : Node_Id;
4593 Target_Type : Entity_Id;
4594 Reason : RT_Exception_Code)
4596 Loc : constant Source_Ptr := Sloc (N);
4597 Source_Type : constant Entity_Id := Etype (N);
4598 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
4599 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
4601 begin
4602 -- First special case, if the source type is already within the range
4603 -- of the target type, then no check is needed (probably we should have
4604 -- stopped Do_Range_Check from being set in the first place, but better
4605 -- late than later in preventing junk code!
4607 -- We do NOT apply this if the source node is a literal, since in this
4608 -- case the literal has already been labeled as having the subtype of
4609 -- the target.
4611 if In_Subrange_Of (Source_Type, Target_Type)
4612 and then not
4613 (Nkind (N) = N_Integer_Literal
4614 or else
4615 Nkind (N) = N_Real_Literal
4616 or else
4617 Nkind (N) = N_Character_Literal
4618 or else
4619 (Is_Entity_Name (N)
4620 and then Ekind (Entity (N)) = E_Enumeration_Literal))
4621 then
4622 return;
4623 end if;
4625 -- We need a check, so force evaluation of the node, so that it does
4626 -- not get evaluated twice (once for the check, once for the actual
4627 -- reference). Such a double evaluation is always a potential source
4628 -- of inefficiency, and is functionally incorrect in the volatile case.
4630 if not Is_Entity_Name (N)
4631 or else Treat_As_Volatile (Entity (N))
4632 then
4633 Force_Evaluation (N);
4634 end if;
4636 -- The easiest case is when Source_Base_Type and Target_Base_Type are
4637 -- the same since in this case we can simply do a direct check of the
4638 -- value of N against the bounds of Target_Type.
4640 -- [constraint_error when N not in Target_Type]
4642 -- Note: this is by far the most common case, for example all cases of
4643 -- checks on the RHS of assignments are in this category, but not all
4644 -- cases are like this. Notably conversions can involve two types.
4646 if Source_Base_Type = Target_Base_Type then
4647 Insert_Action (N,
4648 Make_Raise_Constraint_Error (Loc,
4649 Condition =>
4650 Make_Not_In (Loc,
4651 Left_Opnd => Duplicate_Subexpr (N),
4652 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4653 Reason => Reason));
4655 -- Next test for the case where the target type is within the bounds
4656 -- of the base type of the source type, since in this case we can
4657 -- simply convert these bounds to the base type of T to do the test.
4659 -- [constraint_error when N not in
4660 -- Source_Base_Type (Target_Type'First)
4661 -- ..
4662 -- Source_Base_Type(Target_Type'Last))]
4664 -- The conversions will always work and need no check
4666 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
4667 -- of converting from an enumeration value to an integer type, such as
4668 -- occurs for the case of generating a range check on Enum'Val(Exp)
4669 -- (which used to be handled by gigi). This is OK, since the conversion
4670 -- itself does not require a check.
4672 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4673 Insert_Action (N,
4674 Make_Raise_Constraint_Error (Loc,
4675 Condition =>
4676 Make_Not_In (Loc,
4677 Left_Opnd => Duplicate_Subexpr (N),
4679 Right_Opnd =>
4680 Make_Range (Loc,
4681 Low_Bound =>
4682 Unchecked_Convert_To (Source_Base_Type,
4683 Make_Attribute_Reference (Loc,
4684 Prefix =>
4685 New_Occurrence_Of (Target_Type, Loc),
4686 Attribute_Name => Name_First)),
4688 High_Bound =>
4689 Unchecked_Convert_To (Source_Base_Type,
4690 Make_Attribute_Reference (Loc,
4691 Prefix =>
4692 New_Occurrence_Of (Target_Type, Loc),
4693 Attribute_Name => Name_Last)))),
4694 Reason => Reason));
4696 -- Note that at this stage we now that the Target_Base_Type is not in
4697 -- the range of the Source_Base_Type (since even the Target_Type itself
4698 -- is not in this range). It could still be the case that Source_Type is
4699 -- in range of the target base type since we have not checked that case.
4701 -- If that is the case, we can freely convert the source to the target,
4702 -- and then test the target result against the bounds.
4704 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4706 -- We make a temporary to hold the value of the converted value
4707 -- (converted to the base type), and then we will do the test against
4708 -- this temporary.
4710 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
4711 -- [constraint_error when Tnn not in Target_Type]
4713 -- Then the conversion itself is replaced by an occurrence of Tnn
4715 declare
4716 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4718 begin
4719 Insert_Actions (N, New_List (
4720 Make_Object_Declaration (Loc,
4721 Defining_Identifier => Tnn,
4722 Object_Definition =>
4723 New_Occurrence_Of (Target_Base_Type, Loc),
4724 Constant_Present => True,
4725 Expression =>
4726 Make_Type_Conversion (Loc,
4727 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4728 Expression => Duplicate_Subexpr (N))),
4730 Make_Raise_Constraint_Error (Loc,
4731 Condition =>
4732 Make_Not_In (Loc,
4733 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4734 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4736 Reason => Reason)));
4738 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4740 -- Set the type of N, because the declaration for Tnn might not
4741 -- be analyzed yet, as is the case if N appears within a record
4742 -- declaration, as a discriminant constraint or expression.
4744 Set_Etype (N, Target_Base_Type);
4745 end;
4747 -- At this stage, we know that we have two scalar types, which are
4748 -- directly convertible, and where neither scalar type has a base
4749 -- range that is in the range of the other scalar type.
4751 -- The only way this can happen is with a signed and unsigned type.
4752 -- So test for these two cases:
4754 else
4755 -- Case of the source is unsigned and the target is signed
4757 if Is_Unsigned_Type (Source_Base_Type)
4758 and then not Is_Unsigned_Type (Target_Base_Type)
4759 then
4760 -- If the source is unsigned and the target is signed, then we
4761 -- know that the source is not shorter than the target (otherwise
4762 -- the source base type would be in the target base type range).
4764 -- In other words, the unsigned type is either the same size as
4765 -- the target, or it is larger. It cannot be smaller.
4767 pragma Assert
4768 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4770 -- We only need to check the low bound if the low bound of the
4771 -- target type is non-negative. If the low bound of the target
4772 -- type is negative, then we know that we will fit fine.
4774 -- If the high bound of the target type is negative, then we
4775 -- know we have a constraint error, since we can't possibly
4776 -- have a negative source.
4778 -- With these two checks out of the way, we can do the check
4779 -- using the source type safely
4781 -- This is definitely the most annoying case!
4783 -- [constraint_error
4784 -- when (Target_Type'First >= 0
4785 -- and then
4786 -- N < Source_Base_Type (Target_Type'First))
4787 -- or else Target_Type'Last < 0
4788 -- or else N > Source_Base_Type (Target_Type'Last)];
4790 -- We turn off all checks since we know that the conversions
4791 -- will work fine, given the guards for negative values.
4793 Insert_Action (N,
4794 Make_Raise_Constraint_Error (Loc,
4795 Condition =>
4796 Make_Or_Else (Loc,
4797 Make_Or_Else (Loc,
4798 Left_Opnd =>
4799 Make_And_Then (Loc,
4800 Left_Opnd => Make_Op_Ge (Loc,
4801 Left_Opnd =>
4802 Make_Attribute_Reference (Loc,
4803 Prefix =>
4804 New_Occurrence_Of (Target_Type, Loc),
4805 Attribute_Name => Name_First),
4806 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4808 Right_Opnd =>
4809 Make_Op_Lt (Loc,
4810 Left_Opnd => Duplicate_Subexpr (N),
4811 Right_Opnd =>
4812 Convert_To (Source_Base_Type,
4813 Make_Attribute_Reference (Loc,
4814 Prefix =>
4815 New_Occurrence_Of (Target_Type, Loc),
4816 Attribute_Name => Name_First)))),
4818 Right_Opnd =>
4819 Make_Op_Lt (Loc,
4820 Left_Opnd =>
4821 Make_Attribute_Reference (Loc,
4822 Prefix => New_Occurrence_Of (Target_Type, Loc),
4823 Attribute_Name => Name_Last),
4824 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4826 Right_Opnd =>
4827 Make_Op_Gt (Loc,
4828 Left_Opnd => Duplicate_Subexpr (N),
4829 Right_Opnd =>
4830 Convert_To (Source_Base_Type,
4831 Make_Attribute_Reference (Loc,
4832 Prefix => New_Occurrence_Of (Target_Type, Loc),
4833 Attribute_Name => Name_Last)))),
4835 Reason => Reason),
4836 Suppress => All_Checks);
4838 -- Only remaining possibility is that the source is signed and
4839 -- the target is unsigned.
4841 else
4842 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4843 and then Is_Unsigned_Type (Target_Base_Type));
4845 -- If the source is signed and the target is unsigned, then we
4846 -- know that the target is not shorter than the source (otherwise
4847 -- the target base type would be in the source base type range).
4849 -- In other words, the unsigned type is either the same size as
4850 -- the target, or it is larger. It cannot be smaller.
4852 -- Clearly we have an error if the source value is negative since
4853 -- no unsigned type can have negative values. If the source type
4854 -- is non-negative, then the check can be done using the target
4855 -- type.
4857 -- Tnn : constant Target_Base_Type (N) := Target_Type;
4859 -- [constraint_error
4860 -- when N < 0 or else Tnn not in Target_Type];
4862 -- We turn off all checks for the conversion of N to the target
4863 -- base type, since we generate the explicit check to ensure that
4864 -- the value is non-negative
4866 declare
4867 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4869 begin
4870 Insert_Actions (N, New_List (
4871 Make_Object_Declaration (Loc,
4872 Defining_Identifier => Tnn,
4873 Object_Definition =>
4874 New_Occurrence_Of (Target_Base_Type, Loc),
4875 Constant_Present => True,
4876 Expression =>
4877 Make_Unchecked_Type_Conversion (Loc,
4878 Subtype_Mark =>
4879 New_Occurrence_Of (Target_Base_Type, Loc),
4880 Expression => Duplicate_Subexpr (N))),
4882 Make_Raise_Constraint_Error (Loc,
4883 Condition =>
4884 Make_Or_Else (Loc,
4885 Left_Opnd =>
4886 Make_Op_Lt (Loc,
4887 Left_Opnd => Duplicate_Subexpr (N),
4888 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4890 Right_Opnd =>
4891 Make_Not_In (Loc,
4892 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4893 Right_Opnd =>
4894 New_Occurrence_Of (Target_Type, Loc))),
4896 Reason => Reason)),
4897 Suppress => All_Checks);
4899 -- Set the Etype explicitly, because Insert_Actions may have
4900 -- placed the declaration in the freeze list for an enclosing
4901 -- construct, and thus it is not analyzed yet.
4903 Set_Etype (Tnn, Target_Base_Type);
4904 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4905 end;
4906 end if;
4907 end if;
4908 end Generate_Range_Check;
4910 ------------------
4911 -- Get_Check_Id --
4912 ------------------
4914 function Get_Check_Id (N : Name_Id) return Check_Id is
4915 begin
4916 -- For standard check name, we can do a direct computation
4918 if N in First_Check_Name .. Last_Check_Name then
4919 return Check_Id (N - (First_Check_Name - 1));
4921 -- For non-standard names added by pragma Check_Name, search table
4923 else
4924 for J in All_Checks + 1 .. Check_Names.Last loop
4925 if Check_Names.Table (J) = N then
4926 return J;
4927 end if;
4928 end loop;
4929 end if;
4931 -- No matching name found
4933 return No_Check_Id;
4934 end Get_Check_Id;
4936 ---------------------
4937 -- Get_Discriminal --
4938 ---------------------
4940 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4941 Loc : constant Source_Ptr := Sloc (E);
4942 D : Entity_Id;
4943 Sc : Entity_Id;
4945 begin
4946 -- The bound can be a bona fide parameter of a protected operation,
4947 -- rather than a prival encoded as an in-parameter.
4949 if No (Discriminal_Link (Entity (Bound))) then
4950 return Bound;
4951 end if;
4953 -- Climb the scope stack looking for an enclosing protected type. If
4954 -- we run out of scopes, return the bound itself.
4956 Sc := Scope (E);
4957 while Present (Sc) loop
4958 if Sc = Standard_Standard then
4959 return Bound;
4961 elsif Ekind (Sc) = E_Protected_Type then
4962 exit;
4963 end if;
4965 Sc := Scope (Sc);
4966 end loop;
4968 D := First_Discriminant (Sc);
4969 while Present (D) loop
4970 if Chars (D) = Chars (Bound) then
4971 return New_Occurrence_Of (Discriminal (D), Loc);
4972 end if;
4974 Next_Discriminant (D);
4975 end loop;
4977 return Bound;
4978 end Get_Discriminal;
4980 ----------------------
4981 -- Get_Range_Checks --
4982 ----------------------
4984 function Get_Range_Checks
4985 (Ck_Node : Node_Id;
4986 Target_Typ : Entity_Id;
4987 Source_Typ : Entity_Id := Empty;
4988 Warn_Node : Node_Id := Empty) return Check_Result
4990 begin
4991 return Selected_Range_Checks
4992 (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
4993 end Get_Range_Checks;
4995 ------------------
4996 -- Guard_Access --
4997 ------------------
4999 function Guard_Access
5000 (Cond : Node_Id;
5001 Loc : Source_Ptr;
5002 Ck_Node : Node_Id) return Node_Id
5004 begin
5005 if Nkind (Cond) = N_Or_Else then
5006 Set_Paren_Count (Cond, 1);
5007 end if;
5009 if Nkind (Ck_Node) = N_Allocator then
5010 return Cond;
5011 else
5012 return
5013 Make_And_Then (Loc,
5014 Left_Opnd =>
5015 Make_Op_Ne (Loc,
5016 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
5017 Right_Opnd => Make_Null (Loc)),
5018 Right_Opnd => Cond);
5019 end if;
5020 end Guard_Access;
5022 -----------------------------
5023 -- Index_Checks_Suppressed --
5024 -----------------------------
5026 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
5027 begin
5028 if Present (E) and then Checks_May_Be_Suppressed (E) then
5029 return Is_Check_Suppressed (E, Index_Check);
5030 else
5031 return Scope_Suppress (Index_Check);
5032 end if;
5033 end Index_Checks_Suppressed;
5035 ----------------
5036 -- Initialize --
5037 ----------------
5039 procedure Initialize is
5040 begin
5041 for J in Determine_Range_Cache_N'Range loop
5042 Determine_Range_Cache_N (J) := Empty;
5043 end loop;
5045 Check_Names.Init;
5047 for J in Int range 1 .. All_Checks loop
5048 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
5049 end loop;
5050 end Initialize;
5052 -------------------------
5053 -- Insert_Range_Checks --
5054 -------------------------
5056 procedure Insert_Range_Checks
5057 (Checks : Check_Result;
5058 Node : Node_Id;
5059 Suppress_Typ : Entity_Id;
5060 Static_Sloc : Source_Ptr := No_Location;
5061 Flag_Node : Node_Id := Empty;
5062 Do_Before : Boolean := False)
5064 Internal_Flag_Node : Node_Id := Flag_Node;
5065 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
5067 Check_Node : Node_Id;
5068 Checks_On : constant Boolean :=
5069 (not Index_Checks_Suppressed (Suppress_Typ))
5070 or else
5071 (not Range_Checks_Suppressed (Suppress_Typ));
5073 begin
5074 -- For now we just return if Checks_On is false, however this should be
5075 -- enhanced to check for an always True value in the condition and to
5076 -- generate a compilation warning???
5078 if not Expander_Active or else not Checks_On then
5079 return;
5080 end if;
5082 if Static_Sloc = No_Location then
5083 Internal_Static_Sloc := Sloc (Node);
5084 end if;
5086 if No (Flag_Node) then
5087 Internal_Flag_Node := Node;
5088 end if;
5090 for J in 1 .. 2 loop
5091 exit when No (Checks (J));
5093 if Nkind (Checks (J)) = N_Raise_Constraint_Error
5094 and then Present (Condition (Checks (J)))
5095 then
5096 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
5097 Check_Node := Checks (J);
5098 Mark_Rewrite_Insertion (Check_Node);
5100 if Do_Before then
5101 Insert_Before_And_Analyze (Node, Check_Node);
5102 else
5103 Insert_After_And_Analyze (Node, Check_Node);
5104 end if;
5106 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
5107 end if;
5109 else
5110 Check_Node :=
5111 Make_Raise_Constraint_Error (Internal_Static_Sloc,
5112 Reason => CE_Range_Check_Failed);
5113 Mark_Rewrite_Insertion (Check_Node);
5115 if Do_Before then
5116 Insert_Before_And_Analyze (Node, Check_Node);
5117 else
5118 Insert_After_And_Analyze (Node, Check_Node);
5119 end if;
5120 end if;
5121 end loop;
5122 end Insert_Range_Checks;
5124 ------------------------
5125 -- Insert_Valid_Check --
5126 ------------------------
5128 procedure Insert_Valid_Check (Expr : Node_Id) is
5129 Loc : constant Source_Ptr := Sloc (Expr);
5130 Exp : Node_Id;
5132 begin
5133 -- Do not insert if checks off, or if not checking validity or
5134 -- if expression is known to be valid
5136 if not Validity_Checks_On
5137 or else Range_Or_Validity_Checks_Suppressed (Expr)
5138 or else Expr_Known_Valid (Expr)
5139 then
5140 return;
5141 end if;
5143 -- If we have a checked conversion, then validity check applies to
5144 -- the expression inside the conversion, not the result, since if
5145 -- the expression inside is valid, then so is the conversion result.
5147 Exp := Expr;
5148 while Nkind (Exp) = N_Type_Conversion loop
5149 Exp := Expression (Exp);
5150 end loop;
5152 -- We are about to insert the validity check for Exp. We save and
5153 -- reset the Do_Range_Check flag over this validity check, and then
5154 -- put it back for the final original reference (Exp may be rewritten).
5156 declare
5157 DRC : constant Boolean := Do_Range_Check (Exp);
5159 begin
5160 Set_Do_Range_Check (Exp, False);
5162 -- Force evaluation to avoid multiple reads for atomic/volatile
5164 if Is_Entity_Name (Exp)
5165 and then Is_Volatile (Entity (Exp))
5166 then
5167 Force_Evaluation (Exp, Name_Req => True);
5168 end if;
5170 -- Insert the validity check. Note that we do this with validity
5171 -- checks turned off, to avoid recursion, we do not want validity
5172 -- checks on the validity checking code itself!
5174 Insert_Action
5175 (Expr,
5176 Make_Raise_Constraint_Error (Loc,
5177 Condition =>
5178 Make_Op_Not (Loc,
5179 Right_Opnd =>
5180 Make_Attribute_Reference (Loc,
5181 Prefix =>
5182 Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
5183 Attribute_Name => Name_Valid)),
5184 Reason => CE_Invalid_Data),
5185 Suppress => Validity_Check);
5187 -- If the expression is a a reference to an element of a bit-packed
5188 -- array, then it is rewritten as a renaming declaration. If the
5189 -- expression is an actual in a call, it has not been expanded,
5190 -- waiting for the proper point at which to do it. The same happens
5191 -- with renamings, so that we have to force the expansion now. This
5192 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
5193 -- and exp_ch6.adb.
5195 if Is_Entity_Name (Exp)
5196 and then Nkind (Parent (Entity (Exp))) =
5197 N_Object_Renaming_Declaration
5198 then
5199 declare
5200 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
5201 begin
5202 if Nkind (Old_Exp) = N_Indexed_Component
5203 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
5204 then
5205 Expand_Packed_Element_Reference (Old_Exp);
5206 end if;
5207 end;
5208 end if;
5210 -- Put back the Do_Range_Check flag on the resulting (possibly
5211 -- rewritten) expression.
5213 -- Note: it might be thought that a validity check is not required
5214 -- when a range check is present, but that's not the case, because
5215 -- the back end is allowed to assume for the range check that the
5216 -- operand is within its declared range (an assumption that validity
5217 -- checking is all about NOT assuming!)
5219 -- Note: no need to worry about Possible_Local_Raise here, it will
5220 -- already have been called if original node has Do_Range_Check set.
5222 Set_Do_Range_Check (Exp, DRC);
5223 end;
5224 end Insert_Valid_Check;
5226 ----------------------------------
5227 -- Install_Null_Excluding_Check --
5228 ----------------------------------
5230 procedure Install_Null_Excluding_Check (N : Node_Id) is
5231 Loc : constant Source_Ptr := Sloc (N);
5232 Typ : constant Entity_Id := Etype (N);
5234 function Safe_To_Capture_In_Parameter_Value return Boolean;
5235 -- Determines if it is safe to capture Known_Non_Null status for an
5236 -- the entity referenced by node N. The caller ensures that N is indeed
5237 -- an entity name. It is safe to capture the non-null status for an IN
5238 -- parameter when the reference occurs within a declaration that is sure
5239 -- to be executed as part of the declarative region.
5241 procedure Mark_Non_Null;
5242 -- After installation of check, if the node in question is an entity
5243 -- name, then mark this entity as non-null if possible.
5245 function Safe_To_Capture_In_Parameter_Value return Boolean is
5246 E : constant Entity_Id := Entity (N);
5247 S : constant Entity_Id := Current_Scope;
5248 S_Par : Node_Id;
5250 begin
5251 if Ekind (E) /= E_In_Parameter then
5252 return False;
5253 end if;
5255 -- Two initial context checks. We must be inside a subprogram body
5256 -- with declarations and reference must not appear in nested scopes.
5258 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
5259 or else Scope (E) /= S
5260 then
5261 return False;
5262 end if;
5264 S_Par := Parent (Parent (S));
5266 if Nkind (S_Par) /= N_Subprogram_Body
5267 or else No (Declarations (S_Par))
5268 then
5269 return False;
5270 end if;
5272 declare
5273 N_Decl : Node_Id;
5274 P : Node_Id;
5276 begin
5277 -- Retrieve the declaration node of N (if any). Note that N
5278 -- may be a part of a complex initialization expression.
5280 P := Parent (N);
5281 N_Decl := Empty;
5282 while Present (P) loop
5284 -- If we have a short circuit form, and we are within the right
5285 -- hand expression, we return false, since the right hand side
5286 -- is not guaranteed to be elaborated.
5288 if Nkind (P) in N_Short_Circuit
5289 and then N = Right_Opnd (P)
5290 then
5291 return False;
5292 end if;
5294 -- Similarly, if we are in a conditional expression and not
5295 -- part of the condition, then we return False, since neither
5296 -- the THEN or ELSE expressions will always be elaborated.
5298 if Nkind (P) = N_Conditional_Expression
5299 and then N /= First (Expressions (P))
5300 then
5301 return False;
5302 end if;
5304 -- If we are in a case eexpression, and not part of the
5305 -- expression, then we return False, since a particular
5306 -- branch may not always be elaborated
5308 if Nkind (P) = N_Case_Expression
5309 and then N /= Expression (P)
5310 then
5311 return False;
5312 end if;
5314 -- While traversing the parent chain, we find that N
5315 -- belongs to a statement, thus it may never appear in
5316 -- a declarative region.
5318 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5319 or else Nkind (P) = N_Procedure_Call_Statement
5320 then
5321 return False;
5322 end if;
5324 -- If we are at a declaration, record it and exit
5326 if Nkind (P) in N_Declaration
5327 and then Nkind (P) not in N_Subprogram_Specification
5328 then
5329 N_Decl := P;
5330 exit;
5331 end if;
5333 P := Parent (P);
5334 end loop;
5336 if No (N_Decl) then
5337 return False;
5338 end if;
5340 return List_Containing (N_Decl) = Declarations (S_Par);
5341 end;
5342 end Safe_To_Capture_In_Parameter_Value;
5344 -------------------
5345 -- Mark_Non_Null --
5346 -------------------
5348 procedure Mark_Non_Null is
5349 begin
5350 -- Only case of interest is if node N is an entity name
5352 if Is_Entity_Name (N) then
5354 -- For sure, we want to clear an indication that this is known to
5355 -- be null, since if we get past this check, it definitely is not!
5357 Set_Is_Known_Null (Entity (N), False);
5359 -- We can mark the entity as known to be non-null if either it is
5360 -- safe to capture the value, or in the case of an IN parameter,
5361 -- which is a constant, if the check we just installed is in the
5362 -- declarative region of the subprogram body. In this latter case,
5363 -- a check is decisive for the rest of the body if the expression
5364 -- is sure to be elaborated, since we know we have to elaborate
5365 -- all declarations before executing the body.
5367 -- Couldn't this always be part of Safe_To_Capture_Value ???
5369 if Safe_To_Capture_Value (N, Entity (N))
5370 or else Safe_To_Capture_In_Parameter_Value
5371 then
5372 Set_Is_Known_Non_Null (Entity (N));
5373 end if;
5374 end if;
5375 end Mark_Non_Null;
5377 -- Start of processing for Install_Null_Excluding_Check
5379 begin
5380 pragma Assert (Is_Access_Type (Typ));
5382 -- No check inside a generic (why not???)
5384 if Inside_A_Generic then
5385 return;
5386 end if;
5388 -- No check needed if known to be non-null
5390 if Known_Non_Null (N) then
5391 return;
5392 end if;
5394 -- If known to be null, here is where we generate a compile time check
5396 if Known_Null (N) then
5398 -- Avoid generating warning message inside init procs
5400 if not Inside_Init_Proc then
5401 Apply_Compile_Time_Constraint_Error
5403 "null value not allowed here?",
5404 CE_Access_Check_Failed);
5405 else
5406 Insert_Action (N,
5407 Make_Raise_Constraint_Error (Loc,
5408 Reason => CE_Access_Check_Failed));
5409 end if;
5411 Mark_Non_Null;
5412 return;
5413 end if;
5415 -- If entity is never assigned, for sure a warning is appropriate
5417 if Is_Entity_Name (N) then
5418 Check_Unset_Reference (N);
5419 end if;
5421 -- No check needed if checks are suppressed on the range. Note that we
5422 -- don't set Is_Known_Non_Null in this case (we could legitimately do
5423 -- so, since the program is erroneous, but we don't like to casually
5424 -- propagate such conclusions from erroneosity).
5426 if Access_Checks_Suppressed (Typ) then
5427 return;
5428 end if;
5430 -- No check needed for access to concurrent record types generated by
5431 -- the expander. This is not just an optimization (though it does indeed
5432 -- remove junk checks). It also avoids generation of junk warnings.
5434 if Nkind (N) in N_Has_Chars
5435 and then Chars (N) = Name_uObject
5436 and then Is_Concurrent_Record_Type
5437 (Directly_Designated_Type (Etype (N)))
5438 then
5439 return;
5440 end if;
5442 -- Otherwise install access check
5444 Insert_Action (N,
5445 Make_Raise_Constraint_Error (Loc,
5446 Condition =>
5447 Make_Op_Eq (Loc,
5448 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
5449 Right_Opnd => Make_Null (Loc)),
5450 Reason => CE_Access_Check_Failed));
5452 Mark_Non_Null;
5453 end Install_Null_Excluding_Check;
5455 --------------------------
5456 -- Install_Static_Check --
5457 --------------------------
5459 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5460 Stat : constant Boolean := Is_Static_Expression (R_Cno);
5461 Typ : constant Entity_Id := Etype (R_Cno);
5463 begin
5464 Rewrite (R_Cno,
5465 Make_Raise_Constraint_Error (Loc,
5466 Reason => CE_Range_Check_Failed));
5467 Set_Analyzed (R_Cno);
5468 Set_Etype (R_Cno, Typ);
5469 Set_Raises_Constraint_Error (R_Cno);
5470 Set_Is_Static_Expression (R_Cno, Stat);
5472 -- Now deal with possible local raise handling
5474 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
5475 end Install_Static_Check;
5477 ---------------------
5478 -- Kill_All_Checks --
5479 ---------------------
5481 procedure Kill_All_Checks is
5482 begin
5483 if Debug_Flag_CC then
5484 w ("Kill_All_Checks");
5485 end if;
5487 -- We reset the number of saved checks to zero, and also modify all
5488 -- stack entries for statement ranges to indicate that the number of
5489 -- checks at each level is now zero.
5491 Num_Saved_Checks := 0;
5493 -- Note: the Int'Min here avoids any possibility of J being out of
5494 -- range when called from e.g. Conditional_Statements_Begin.
5496 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
5497 Saved_Checks_Stack (J) := 0;
5498 end loop;
5499 end Kill_All_Checks;
5501 -----------------
5502 -- Kill_Checks --
5503 -----------------
5505 procedure Kill_Checks (V : Entity_Id) is
5506 begin
5507 if Debug_Flag_CC then
5508 w ("Kill_Checks for entity", Int (V));
5509 end if;
5511 for J in 1 .. Num_Saved_Checks loop
5512 if Saved_Checks (J).Entity = V then
5513 if Debug_Flag_CC then
5514 w (" Checks killed for saved check ", J);
5515 end if;
5517 Saved_Checks (J).Killed := True;
5518 end if;
5519 end loop;
5520 end Kill_Checks;
5522 ------------------------------
5523 -- Length_Checks_Suppressed --
5524 ------------------------------
5526 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5527 begin
5528 if Present (E) and then Checks_May_Be_Suppressed (E) then
5529 return Is_Check_Suppressed (E, Length_Check);
5530 else
5531 return Scope_Suppress (Length_Check);
5532 end if;
5533 end Length_Checks_Suppressed;
5535 --------------------------------
5536 -- Overflow_Checks_Suppressed --
5537 --------------------------------
5539 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5540 begin
5541 if Present (E) and then Checks_May_Be_Suppressed (E) then
5542 return Is_Check_Suppressed (E, Overflow_Check);
5543 else
5544 return Scope_Suppress (Overflow_Check);
5545 end if;
5546 end Overflow_Checks_Suppressed;
5548 -----------------------------
5549 -- Range_Checks_Suppressed --
5550 -----------------------------
5552 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5553 begin
5554 if Present (E) then
5556 -- Note: for now we always suppress range checks on Vax float types,
5557 -- since Gigi does not know how to generate these checks.
5559 if Vax_Float (E) then
5560 return True;
5561 elsif Kill_Range_Checks (E) then
5562 return True;
5563 elsif Checks_May_Be_Suppressed (E) then
5564 return Is_Check_Suppressed (E, Range_Check);
5565 end if;
5566 end if;
5568 return Scope_Suppress (Range_Check);
5569 end Range_Checks_Suppressed;
5571 -----------------------------------------
5572 -- Range_Or_Validity_Checks_Suppressed --
5573 -----------------------------------------
5575 -- Note: the coding would be simpler here if we simply made appropriate
5576 -- calls to Range/Validity_Checks_Suppressed, but that would result in
5577 -- duplicated checks which we prefer to avoid.
5579 function Range_Or_Validity_Checks_Suppressed
5580 (Expr : Node_Id) return Boolean
5582 begin
5583 -- Immediate return if scope checks suppressed for either check
5585 if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5586 return True;
5587 end if;
5589 -- If no expression, that's odd, decide that checks are suppressed,
5590 -- since we don't want anyone trying to do checks in this case, which
5591 -- is most likely the result of some other error.
5593 if No (Expr) then
5594 return True;
5595 end if;
5597 -- Expression is present, so perform suppress checks on type
5599 declare
5600 Typ : constant Entity_Id := Etype (Expr);
5601 begin
5602 if Vax_Float (Typ) then
5603 return True;
5604 elsif Checks_May_Be_Suppressed (Typ)
5605 and then (Is_Check_Suppressed (Typ, Range_Check)
5606 or else
5607 Is_Check_Suppressed (Typ, Validity_Check))
5608 then
5609 return True;
5610 end if;
5611 end;
5613 -- If expression is an entity name, perform checks on this entity
5615 if Is_Entity_Name (Expr) then
5616 declare
5617 Ent : constant Entity_Id := Entity (Expr);
5618 begin
5619 if Checks_May_Be_Suppressed (Ent) then
5620 return Is_Check_Suppressed (Ent, Range_Check)
5621 or else Is_Check_Suppressed (Ent, Validity_Check);
5622 end if;
5623 end;
5624 end if;
5626 -- If we fall through, no checks suppressed
5628 return False;
5629 end Range_Or_Validity_Checks_Suppressed;
5631 -------------------
5632 -- Remove_Checks --
5633 -------------------
5635 procedure Remove_Checks (Expr : Node_Id) is
5636 function Process (N : Node_Id) return Traverse_Result;
5637 -- Process a single node during the traversal
5639 procedure Traverse is new Traverse_Proc (Process);
5640 -- The traversal procedure itself
5642 -------------
5643 -- Process --
5644 -------------
5646 function Process (N : Node_Id) return Traverse_Result is
5647 begin
5648 if Nkind (N) not in N_Subexpr then
5649 return Skip;
5650 end if;
5652 Set_Do_Range_Check (N, False);
5654 case Nkind (N) is
5655 when N_And_Then =>
5656 Traverse (Left_Opnd (N));
5657 return Skip;
5659 when N_Attribute_Reference =>
5660 Set_Do_Overflow_Check (N, False);
5662 when N_Function_Call =>
5663 Set_Do_Tag_Check (N, False);
5665 when N_Op =>
5666 Set_Do_Overflow_Check (N, False);
5668 case Nkind (N) is
5669 when N_Op_Divide =>
5670 Set_Do_Division_Check (N, False);
5672 when N_Op_And =>
5673 Set_Do_Length_Check (N, False);
5675 when N_Op_Mod =>
5676 Set_Do_Division_Check (N, False);
5678 when N_Op_Or =>
5679 Set_Do_Length_Check (N, False);
5681 when N_Op_Rem =>
5682 Set_Do_Division_Check (N, False);
5684 when N_Op_Xor =>
5685 Set_Do_Length_Check (N, False);
5687 when others =>
5688 null;
5689 end case;
5691 when N_Or_Else =>
5692 Traverse (Left_Opnd (N));
5693 return Skip;
5695 when N_Selected_Component =>
5696 Set_Do_Discriminant_Check (N, False);
5698 when N_Type_Conversion =>
5699 Set_Do_Length_Check (N, False);
5700 Set_Do_Tag_Check (N, False);
5701 Set_Do_Overflow_Check (N, False);
5703 when others =>
5704 null;
5705 end case;
5707 return OK;
5708 end Process;
5710 -- Start of processing for Remove_Checks
5712 begin
5713 Traverse (Expr);
5714 end Remove_Checks;
5716 ----------------------------
5717 -- Selected_Length_Checks --
5718 ----------------------------
5720 function Selected_Length_Checks
5721 (Ck_Node : Node_Id;
5722 Target_Typ : Entity_Id;
5723 Source_Typ : Entity_Id;
5724 Warn_Node : Node_Id) return Check_Result
5726 Loc : constant Source_Ptr := Sloc (Ck_Node);
5727 S_Typ : Entity_Id;
5728 T_Typ : Entity_Id;
5729 Expr_Actual : Node_Id;
5730 Exptyp : Entity_Id;
5731 Cond : Node_Id := Empty;
5732 Do_Access : Boolean := False;
5733 Wnode : Node_Id := Warn_Node;
5734 Ret_Result : Check_Result := (Empty, Empty);
5735 Num_Checks : Natural := 0;
5737 procedure Add_Check (N : Node_Id);
5738 -- Adds the action given to Ret_Result if N is non-Empty
5740 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5741 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5742 -- Comments required ???
5744 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5745 -- True for equal literals and for nodes that denote the same constant
5746 -- entity, even if its value is not a static constant. This includes the
5747 -- case of a discriminal reference within an init proc. Removes some
5748 -- obviously superfluous checks.
5750 function Length_E_Cond
5751 (Exptyp : Entity_Id;
5752 Typ : Entity_Id;
5753 Indx : Nat) return Node_Id;
5754 -- Returns expression to compute:
5755 -- Typ'Length /= Exptyp'Length
5757 function Length_N_Cond
5758 (Expr : Node_Id;
5759 Typ : Entity_Id;
5760 Indx : Nat) return Node_Id;
5761 -- Returns expression to compute:
5762 -- Typ'Length /= Expr'Length
5764 ---------------
5765 -- Add_Check --
5766 ---------------
5768 procedure Add_Check (N : Node_Id) is
5769 begin
5770 if Present (N) then
5772 -- For now, ignore attempt to place more than 2 checks ???
5774 if Num_Checks = 2 then
5775 return;
5776 end if;
5778 pragma Assert (Num_Checks <= 1);
5779 Num_Checks := Num_Checks + 1;
5780 Ret_Result (Num_Checks) := N;
5781 end if;
5782 end Add_Check;
5784 ------------------
5785 -- Get_E_Length --
5786 ------------------
5788 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5789 SE : constant Entity_Id := Scope (E);
5790 N : Node_Id;
5791 E1 : Entity_Id := E;
5793 begin
5794 if Ekind (Scope (E)) = E_Record_Type
5795 and then Has_Discriminants (Scope (E))
5796 then
5797 N := Build_Discriminal_Subtype_Of_Component (E);
5799 if Present (N) then
5800 Insert_Action (Ck_Node, N);
5801 E1 := Defining_Identifier (N);
5802 end if;
5803 end if;
5805 if Ekind (E1) = E_String_Literal_Subtype then
5806 return
5807 Make_Integer_Literal (Loc,
5808 Intval => String_Literal_Length (E1));
5810 elsif SE /= Standard_Standard
5811 and then Ekind (Scope (SE)) = E_Protected_Type
5812 and then Has_Discriminants (Scope (SE))
5813 and then Has_Completion (Scope (SE))
5814 and then not Inside_Init_Proc
5815 then
5816 -- If the type whose length is needed is a private component
5817 -- constrained by a discriminant, we must expand the 'Length
5818 -- attribute into an explicit computation, using the discriminal
5819 -- of the current protected operation. This is because the actual
5820 -- type of the prival is constructed after the protected opera-
5821 -- tion has been fully expanded.
5823 declare
5824 Indx_Type : Node_Id;
5825 Lo : Node_Id;
5826 Hi : Node_Id;
5827 Do_Expand : Boolean := False;
5829 begin
5830 Indx_Type := First_Index (E);
5832 for J in 1 .. Indx - 1 loop
5833 Next_Index (Indx_Type);
5834 end loop;
5836 Get_Index_Bounds (Indx_Type, Lo, Hi);
5838 if Nkind (Lo) = N_Identifier
5839 and then Ekind (Entity (Lo)) = E_In_Parameter
5840 then
5841 Lo := Get_Discriminal (E, Lo);
5842 Do_Expand := True;
5843 end if;
5845 if Nkind (Hi) = N_Identifier
5846 and then Ekind (Entity (Hi)) = E_In_Parameter
5847 then
5848 Hi := Get_Discriminal (E, Hi);
5849 Do_Expand := True;
5850 end if;
5852 if Do_Expand then
5853 if not Is_Entity_Name (Lo) then
5854 Lo := Duplicate_Subexpr_No_Checks (Lo);
5855 end if;
5857 if not Is_Entity_Name (Hi) then
5858 Lo := Duplicate_Subexpr_No_Checks (Hi);
5859 end if;
5861 N :=
5862 Make_Op_Add (Loc,
5863 Left_Opnd =>
5864 Make_Op_Subtract (Loc,
5865 Left_Opnd => Hi,
5866 Right_Opnd => Lo),
5868 Right_Opnd => Make_Integer_Literal (Loc, 1));
5869 return N;
5871 else
5872 N :=
5873 Make_Attribute_Reference (Loc,
5874 Attribute_Name => Name_Length,
5875 Prefix =>
5876 New_Occurrence_Of (E1, Loc));
5878 if Indx > 1 then
5879 Set_Expressions (N, New_List (
5880 Make_Integer_Literal (Loc, Indx)));
5881 end if;
5883 return N;
5884 end if;
5885 end;
5887 else
5888 N :=
5889 Make_Attribute_Reference (Loc,
5890 Attribute_Name => Name_Length,
5891 Prefix =>
5892 New_Occurrence_Of (E1, Loc));
5894 if Indx > 1 then
5895 Set_Expressions (N, New_List (
5896 Make_Integer_Literal (Loc, Indx)));
5897 end if;
5899 return N;
5900 end if;
5901 end Get_E_Length;
5903 ------------------
5904 -- Get_N_Length --
5905 ------------------
5907 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5908 begin
5909 return
5910 Make_Attribute_Reference (Loc,
5911 Attribute_Name => Name_Length,
5912 Prefix =>
5913 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5914 Expressions => New_List (
5915 Make_Integer_Literal (Loc, Indx)));
5916 end Get_N_Length;
5918 -------------------
5919 -- Length_E_Cond --
5920 -------------------
5922 function Length_E_Cond
5923 (Exptyp : Entity_Id;
5924 Typ : Entity_Id;
5925 Indx : Nat) return Node_Id
5927 begin
5928 return
5929 Make_Op_Ne (Loc,
5930 Left_Opnd => Get_E_Length (Typ, Indx),
5931 Right_Opnd => Get_E_Length (Exptyp, Indx));
5932 end Length_E_Cond;
5934 -------------------
5935 -- Length_N_Cond --
5936 -------------------
5938 function Length_N_Cond
5939 (Expr : Node_Id;
5940 Typ : Entity_Id;
5941 Indx : Nat) return Node_Id
5943 begin
5944 return
5945 Make_Op_Ne (Loc,
5946 Left_Opnd => Get_E_Length (Typ, Indx),
5947 Right_Opnd => Get_N_Length (Expr, Indx));
5948 end Length_N_Cond;
5950 -----------------
5951 -- Same_Bounds --
5952 -----------------
5954 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5955 begin
5956 return
5957 (Nkind (L) = N_Integer_Literal
5958 and then Nkind (R) = N_Integer_Literal
5959 and then Intval (L) = Intval (R))
5961 or else
5962 (Is_Entity_Name (L)
5963 and then Ekind (Entity (L)) = E_Constant
5964 and then ((Is_Entity_Name (R)
5965 and then Entity (L) = Entity (R))
5966 or else
5967 (Nkind (R) = N_Type_Conversion
5968 and then Is_Entity_Name (Expression (R))
5969 and then Entity (L) = Entity (Expression (R)))))
5971 or else
5972 (Is_Entity_Name (R)
5973 and then Ekind (Entity (R)) = E_Constant
5974 and then Nkind (L) = N_Type_Conversion
5975 and then Is_Entity_Name (Expression (L))
5976 and then Entity (R) = Entity (Expression (L)))
5978 or else
5979 (Is_Entity_Name (L)
5980 and then Is_Entity_Name (R)
5981 and then Entity (L) = Entity (R)
5982 and then Ekind (Entity (L)) = E_In_Parameter
5983 and then Inside_Init_Proc);
5984 end Same_Bounds;
5986 -- Start of processing for Selected_Length_Checks
5988 begin
5989 if not Expander_Active then
5990 return Ret_Result;
5991 end if;
5993 if Target_Typ = Any_Type
5994 or else Target_Typ = Any_Composite
5995 or else Raises_Constraint_Error (Ck_Node)
5996 then
5997 return Ret_Result;
5998 end if;
6000 if No (Wnode) then
6001 Wnode := Ck_Node;
6002 end if;
6004 T_Typ := Target_Typ;
6006 if No (Source_Typ) then
6007 S_Typ := Etype (Ck_Node);
6008 else
6009 S_Typ := Source_Typ;
6010 end if;
6012 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6013 return Ret_Result;
6014 end if;
6016 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6017 S_Typ := Designated_Type (S_Typ);
6018 T_Typ := Designated_Type (T_Typ);
6019 Do_Access := True;
6021 -- A simple optimization for the null case
6023 if Known_Null (Ck_Node) then
6024 return Ret_Result;
6025 end if;
6026 end if;
6028 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6029 if Is_Constrained (T_Typ) then
6031 -- The checking code to be generated will freeze the
6032 -- corresponding array type. However, we must freeze the
6033 -- type now, so that the freeze node does not appear within
6034 -- the generated condional expression, but ahead of it.
6036 Freeze_Before (Ck_Node, T_Typ);
6038 Expr_Actual := Get_Referenced_Object (Ck_Node);
6039 Exptyp := Get_Actual_Subtype (Ck_Node);
6041 if Is_Access_Type (Exptyp) then
6042 Exptyp := Designated_Type (Exptyp);
6043 end if;
6045 -- String_Literal case. This needs to be handled specially be-
6046 -- cause no index types are available for string literals. The
6047 -- condition is simply:
6049 -- T_Typ'Length = string-literal-length
6051 if Nkind (Expr_Actual) = N_String_Literal
6052 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
6053 then
6054 Cond :=
6055 Make_Op_Ne (Loc,
6056 Left_Opnd => Get_E_Length (T_Typ, 1),
6057 Right_Opnd =>
6058 Make_Integer_Literal (Loc,
6059 Intval =>
6060 String_Literal_Length (Etype (Expr_Actual))));
6062 -- General array case. Here we have a usable actual subtype for
6063 -- the expression, and the condition is built from the two types
6064 -- (Do_Length):
6066 -- T_Typ'Length /= Exptyp'Length or else
6067 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
6068 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
6069 -- ...
6071 elsif Is_Constrained (Exptyp) then
6072 declare
6073 Ndims : constant Nat := Number_Dimensions (T_Typ);
6075 L_Index : Node_Id;
6076 R_Index : Node_Id;
6077 L_Low : Node_Id;
6078 L_High : Node_Id;
6079 R_Low : Node_Id;
6080 R_High : Node_Id;
6081 L_Length : Uint;
6082 R_Length : Uint;
6083 Ref_Node : Node_Id;
6085 begin
6086 -- At the library level, we need to ensure that the type of
6087 -- the object is elaborated before the check itself is
6088 -- emitted. This is only done if the object is in the
6089 -- current compilation unit, otherwise the type is frozen
6090 -- and elaborated in its unit.
6092 if Is_Itype (Exptyp)
6093 and then
6094 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
6095 and then
6096 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
6097 and then In_Open_Scopes (Scope (Exptyp))
6098 then
6099 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
6100 Set_Itype (Ref_Node, Exptyp);
6101 Insert_Action (Ck_Node, Ref_Node);
6102 end if;
6104 L_Index := First_Index (T_Typ);
6105 R_Index := First_Index (Exptyp);
6107 for Indx in 1 .. Ndims loop
6108 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6109 or else
6110 Nkind (R_Index) = N_Raise_Constraint_Error)
6111 then
6112 Get_Index_Bounds (L_Index, L_Low, L_High);
6113 Get_Index_Bounds (R_Index, R_Low, R_High);
6115 -- Deal with compile time length check. Note that we
6116 -- skip this in the access case, because the access
6117 -- value may be null, so we cannot know statically.
6119 if not Do_Access
6120 and then Compile_Time_Known_Value (L_Low)
6121 and then Compile_Time_Known_Value (L_High)
6122 and then Compile_Time_Known_Value (R_Low)
6123 and then Compile_Time_Known_Value (R_High)
6124 then
6125 if Expr_Value (L_High) >= Expr_Value (L_Low) then
6126 L_Length := Expr_Value (L_High) -
6127 Expr_Value (L_Low) + 1;
6128 else
6129 L_Length := UI_From_Int (0);
6130 end if;
6132 if Expr_Value (R_High) >= Expr_Value (R_Low) then
6133 R_Length := Expr_Value (R_High) -
6134 Expr_Value (R_Low) + 1;
6135 else
6136 R_Length := UI_From_Int (0);
6137 end if;
6139 if L_Length > R_Length then
6140 Add_Check
6141 (Compile_Time_Constraint_Error
6142 (Wnode, "too few elements for}?", T_Typ));
6144 elsif L_Length < R_Length then
6145 Add_Check
6146 (Compile_Time_Constraint_Error
6147 (Wnode, "too many elements for}?", T_Typ));
6148 end if;
6150 -- The comparison for an individual index subtype
6151 -- is omitted if the corresponding index subtypes
6152 -- statically match, since the result is known to
6153 -- be true. Note that this test is worth while even
6154 -- though we do static evaluation, because non-static
6155 -- subtypes can statically match.
6157 elsif not
6158 Subtypes_Statically_Match
6159 (Etype (L_Index), Etype (R_Index))
6161 and then not
6162 (Same_Bounds (L_Low, R_Low)
6163 and then Same_Bounds (L_High, R_High))
6164 then
6165 Evolve_Or_Else
6166 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
6167 end if;
6169 Next (L_Index);
6170 Next (R_Index);
6171 end if;
6172 end loop;
6173 end;
6175 -- Handle cases where we do not get a usable actual subtype that
6176 -- is constrained. This happens for example in the function call
6177 -- and explicit dereference cases. In these cases, we have to get
6178 -- the length or range from the expression itself, making sure we
6179 -- do not evaluate it more than once.
6181 -- Here Ck_Node is the original expression, or more properly the
6182 -- result of applying Duplicate_Expr to the original tree, forcing
6183 -- the result to be a name.
6185 else
6186 declare
6187 Ndims : constant Nat := Number_Dimensions (T_Typ);
6189 begin
6190 -- Build the condition for the explicit dereference case
6192 for Indx in 1 .. Ndims loop
6193 Evolve_Or_Else
6194 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
6195 end loop;
6196 end;
6197 end if;
6198 end if;
6199 end if;
6201 -- Construct the test and insert into the tree
6203 if Present (Cond) then
6204 if Do_Access then
6205 Cond := Guard_Access (Cond, Loc, Ck_Node);
6206 end if;
6208 Add_Check
6209 (Make_Raise_Constraint_Error (Loc,
6210 Condition => Cond,
6211 Reason => CE_Length_Check_Failed));
6212 end if;
6214 return Ret_Result;
6215 end Selected_Length_Checks;
6217 ---------------------------
6218 -- Selected_Range_Checks --
6219 ---------------------------
6221 function Selected_Range_Checks
6222 (Ck_Node : Node_Id;
6223 Target_Typ : Entity_Id;
6224 Source_Typ : Entity_Id;
6225 Warn_Node : Node_Id) return Check_Result
6227 Loc : constant Source_Ptr := Sloc (Ck_Node);
6228 S_Typ : Entity_Id;
6229 T_Typ : Entity_Id;
6230 Expr_Actual : Node_Id;
6231 Exptyp : Entity_Id;
6232 Cond : Node_Id := Empty;
6233 Do_Access : Boolean := False;
6234 Wnode : Node_Id := Warn_Node;
6235 Ret_Result : Check_Result := (Empty, Empty);
6236 Num_Checks : Integer := 0;
6238 procedure Add_Check (N : Node_Id);
6239 -- Adds the action given to Ret_Result if N is non-Empty
6241 function Discrete_Range_Cond
6242 (Expr : Node_Id;
6243 Typ : Entity_Id) return Node_Id;
6244 -- Returns expression to compute:
6245 -- Low_Bound (Expr) < Typ'First
6246 -- or else
6247 -- High_Bound (Expr) > Typ'Last
6249 function Discrete_Expr_Cond
6250 (Expr : Node_Id;
6251 Typ : Entity_Id) return Node_Id;
6252 -- Returns expression to compute:
6253 -- Expr < Typ'First
6254 -- or else
6255 -- Expr > Typ'Last
6257 function Get_E_First_Or_Last
6258 (Loc : Source_Ptr;
6259 E : Entity_Id;
6260 Indx : Nat;
6261 Nam : Name_Id) return Node_Id;
6262 -- Returns an attribute reference
6263 -- E'First or E'Last
6264 -- with a source location of Loc.
6266 -- Nam is Name_First or Name_Last, according to which attribute is
6267 -- desired. If Indx is non-zero, it is passed as a literal in the
6268 -- Expressions of the attribute reference (identifying the desired
6269 -- array dimension).
6271 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
6272 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
6273 -- Returns expression to compute:
6274 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
6276 function Range_E_Cond
6277 (Exptyp : Entity_Id;
6278 Typ : Entity_Id;
6279 Indx : Nat)
6280 return Node_Id;
6281 -- Returns expression to compute:
6282 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
6284 function Range_Equal_E_Cond
6285 (Exptyp : Entity_Id;
6286 Typ : Entity_Id;
6287 Indx : Nat) return Node_Id;
6288 -- Returns expression to compute:
6289 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
6291 function Range_N_Cond
6292 (Expr : Node_Id;
6293 Typ : Entity_Id;
6294 Indx : Nat) return Node_Id;
6295 -- Return expression to compute:
6296 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
6298 ---------------
6299 -- Add_Check --
6300 ---------------
6302 procedure Add_Check (N : Node_Id) is
6303 begin
6304 if Present (N) then
6306 -- For now, ignore attempt to place more than 2 checks ???
6308 if Num_Checks = 2 then
6309 return;
6310 end if;
6312 pragma Assert (Num_Checks <= 1);
6313 Num_Checks := Num_Checks + 1;
6314 Ret_Result (Num_Checks) := N;
6315 end if;
6316 end Add_Check;
6318 -------------------------
6319 -- Discrete_Expr_Cond --
6320 -------------------------
6322 function Discrete_Expr_Cond
6323 (Expr : Node_Id;
6324 Typ : Entity_Id) return Node_Id
6326 begin
6327 return
6328 Make_Or_Else (Loc,
6329 Left_Opnd =>
6330 Make_Op_Lt (Loc,
6331 Left_Opnd =>
6332 Convert_To (Base_Type (Typ),
6333 Duplicate_Subexpr_No_Checks (Expr)),
6334 Right_Opnd =>
6335 Convert_To (Base_Type (Typ),
6336 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
6338 Right_Opnd =>
6339 Make_Op_Gt (Loc,
6340 Left_Opnd =>
6341 Convert_To (Base_Type (Typ),
6342 Duplicate_Subexpr_No_Checks (Expr)),
6343 Right_Opnd =>
6344 Convert_To
6345 (Base_Type (Typ),
6346 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
6347 end Discrete_Expr_Cond;
6349 -------------------------
6350 -- Discrete_Range_Cond --
6351 -------------------------
6353 function Discrete_Range_Cond
6354 (Expr : Node_Id;
6355 Typ : Entity_Id) return Node_Id
6357 LB : Node_Id := Low_Bound (Expr);
6358 HB : Node_Id := High_Bound (Expr);
6360 Left_Opnd : Node_Id;
6361 Right_Opnd : Node_Id;
6363 begin
6364 if Nkind (LB) = N_Identifier
6365 and then Ekind (Entity (LB)) = E_Discriminant
6366 then
6367 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6368 end if;
6370 if Nkind (HB) = N_Identifier
6371 and then Ekind (Entity (HB)) = E_Discriminant
6372 then
6373 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6374 end if;
6376 Left_Opnd :=
6377 Make_Op_Lt (Loc,
6378 Left_Opnd =>
6379 Convert_To
6380 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6382 Right_Opnd =>
6383 Convert_To
6384 (Base_Type (Typ),
6385 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
6387 if Base_Type (Typ) = Typ then
6388 return Left_Opnd;
6390 elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6391 and then
6392 Compile_Time_Known_Value (High_Bound (Scalar_Range
6393 (Base_Type (Typ))))
6394 then
6395 if Is_Floating_Point_Type (Typ) then
6396 if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6397 Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6398 then
6399 return Left_Opnd;
6400 end if;
6402 else
6403 if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6404 Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6405 then
6406 return Left_Opnd;
6407 end if;
6408 end if;
6409 end if;
6411 Right_Opnd :=
6412 Make_Op_Gt (Loc,
6413 Left_Opnd =>
6414 Convert_To
6415 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6417 Right_Opnd =>
6418 Convert_To
6419 (Base_Type (Typ),
6420 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
6422 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6423 end Discrete_Range_Cond;
6425 -------------------------
6426 -- Get_E_First_Or_Last --
6427 -------------------------
6429 function Get_E_First_Or_Last
6430 (Loc : Source_Ptr;
6431 E : Entity_Id;
6432 Indx : Nat;
6433 Nam : Name_Id) return Node_Id
6435 Exprs : List_Id;
6436 begin
6437 if Indx > 0 then
6438 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
6439 else
6440 Exprs := No_List;
6441 end if;
6443 return Make_Attribute_Reference (Loc,
6444 Prefix => New_Occurrence_Of (E, Loc),
6445 Attribute_Name => Nam,
6446 Expressions => Exprs);
6447 end Get_E_First_Or_Last;
6449 -----------------
6450 -- Get_N_First --
6451 -----------------
6453 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6454 begin
6455 return
6456 Make_Attribute_Reference (Loc,
6457 Attribute_Name => Name_First,
6458 Prefix =>
6459 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6460 Expressions => New_List (
6461 Make_Integer_Literal (Loc, Indx)));
6462 end Get_N_First;
6464 ----------------
6465 -- Get_N_Last --
6466 ----------------
6468 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6469 begin
6470 return
6471 Make_Attribute_Reference (Loc,
6472 Attribute_Name => Name_Last,
6473 Prefix =>
6474 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6475 Expressions => New_List (
6476 Make_Integer_Literal (Loc, Indx)));
6477 end Get_N_Last;
6479 ------------------
6480 -- Range_E_Cond --
6481 ------------------
6483 function Range_E_Cond
6484 (Exptyp : Entity_Id;
6485 Typ : Entity_Id;
6486 Indx : Nat) return Node_Id
6488 begin
6489 return
6490 Make_Or_Else (Loc,
6491 Left_Opnd =>
6492 Make_Op_Lt (Loc,
6493 Left_Opnd =>
6494 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6495 Right_Opnd =>
6496 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6498 Right_Opnd =>
6499 Make_Op_Gt (Loc,
6500 Left_Opnd =>
6501 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6502 Right_Opnd =>
6503 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6504 end Range_E_Cond;
6506 ------------------------
6507 -- Range_Equal_E_Cond --
6508 ------------------------
6510 function Range_Equal_E_Cond
6511 (Exptyp : Entity_Id;
6512 Typ : Entity_Id;
6513 Indx : Nat) return Node_Id
6515 begin
6516 return
6517 Make_Or_Else (Loc,
6518 Left_Opnd =>
6519 Make_Op_Ne (Loc,
6520 Left_Opnd =>
6521 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6522 Right_Opnd =>
6523 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6525 Right_Opnd =>
6526 Make_Op_Ne (Loc,
6527 Left_Opnd =>
6528 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6529 Right_Opnd =>
6530 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6531 end Range_Equal_E_Cond;
6533 ------------------
6534 -- Range_N_Cond --
6535 ------------------
6537 function Range_N_Cond
6538 (Expr : Node_Id;
6539 Typ : Entity_Id;
6540 Indx : Nat) return Node_Id
6542 begin
6543 return
6544 Make_Or_Else (Loc,
6545 Left_Opnd =>
6546 Make_Op_Lt (Loc,
6547 Left_Opnd =>
6548 Get_N_First (Expr, Indx),
6549 Right_Opnd =>
6550 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6552 Right_Opnd =>
6553 Make_Op_Gt (Loc,
6554 Left_Opnd =>
6555 Get_N_Last (Expr, Indx),
6556 Right_Opnd =>
6557 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6558 end Range_N_Cond;
6560 -- Start of processing for Selected_Range_Checks
6562 begin
6563 if not Expander_Active then
6564 return Ret_Result;
6565 end if;
6567 if Target_Typ = Any_Type
6568 or else Target_Typ = Any_Composite
6569 or else Raises_Constraint_Error (Ck_Node)
6570 then
6571 return Ret_Result;
6572 end if;
6574 if No (Wnode) then
6575 Wnode := Ck_Node;
6576 end if;
6578 T_Typ := Target_Typ;
6580 if No (Source_Typ) then
6581 S_Typ := Etype (Ck_Node);
6582 else
6583 S_Typ := Source_Typ;
6584 end if;
6586 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6587 return Ret_Result;
6588 end if;
6590 -- The order of evaluating T_Typ before S_Typ seems to be critical
6591 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6592 -- in, and since Node can be an N_Range node, it might be invalid.
6593 -- Should there be an assert check somewhere for taking the Etype of
6594 -- an N_Range node ???
6596 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6597 S_Typ := Designated_Type (S_Typ);
6598 T_Typ := Designated_Type (T_Typ);
6599 Do_Access := True;
6601 -- A simple optimization for the null case
6603 if Known_Null (Ck_Node) then
6604 return Ret_Result;
6605 end if;
6606 end if;
6608 -- For an N_Range Node, check for a null range and then if not
6609 -- null generate a range check action.
6611 if Nkind (Ck_Node) = N_Range then
6613 -- There's no point in checking a range against itself
6615 if Ck_Node = Scalar_Range (T_Typ) then
6616 return Ret_Result;
6617 end if;
6619 declare
6620 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
6621 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
6622 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
6623 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
6625 LB : Node_Id := Low_Bound (Ck_Node);
6626 HB : Node_Id := High_Bound (Ck_Node);
6627 Known_LB : Boolean;
6628 Known_HB : Boolean;
6630 Null_Range : Boolean;
6631 Out_Of_Range_L : Boolean;
6632 Out_Of_Range_H : Boolean;
6634 begin
6635 -- Compute what is known at compile time
6637 if Known_T_LB and Known_T_HB then
6638 if Compile_Time_Known_Value (LB) then
6639 Known_LB := True;
6641 -- There's no point in checking that a bound is within its
6642 -- own range so pretend that it is known in this case. First
6643 -- deal with low bound.
6645 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
6646 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
6647 then
6648 LB := T_LB;
6649 Known_LB := True;
6651 else
6652 Known_LB := False;
6653 end if;
6655 -- Likewise for the high bound
6657 if Compile_Time_Known_Value (HB) then
6658 Known_HB := True;
6660 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
6661 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
6662 then
6663 HB := T_HB;
6664 Known_HB := True;
6666 else
6667 Known_HB := False;
6668 end if;
6669 end if;
6671 -- Check for case where everything is static and we can do the
6672 -- check at compile time. This is skipped if we have an access
6673 -- type, since the access value may be null.
6675 -- ??? This code can be improved since you only need to know that
6676 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
6677 -- compile time to emit pertinent messages.
6679 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
6680 and not Do_Access
6681 then
6682 -- Floating-point case
6684 if Is_Floating_Point_Type (S_Typ) then
6685 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6686 Out_Of_Range_L :=
6687 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6688 or else
6689 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6691 Out_Of_Range_H :=
6692 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6693 or else
6694 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6696 -- Fixed or discrete type case
6698 else
6699 Null_Range := Expr_Value (HB) < Expr_Value (LB);
6700 Out_Of_Range_L :=
6701 (Expr_Value (LB) < Expr_Value (T_LB))
6702 or else
6703 (Expr_Value (LB) > Expr_Value (T_HB));
6705 Out_Of_Range_H :=
6706 (Expr_Value (HB) > Expr_Value (T_HB))
6707 or else
6708 (Expr_Value (HB) < Expr_Value (T_LB));
6709 end if;
6711 if not Null_Range then
6712 if Out_Of_Range_L then
6713 if No (Warn_Node) then
6714 Add_Check
6715 (Compile_Time_Constraint_Error
6716 (Low_Bound (Ck_Node),
6717 "static value out of range of}?", T_Typ));
6719 else
6720 Add_Check
6721 (Compile_Time_Constraint_Error
6722 (Wnode,
6723 "static range out of bounds of}?", T_Typ));
6724 end if;
6725 end if;
6727 if Out_Of_Range_H then
6728 if No (Warn_Node) then
6729 Add_Check
6730 (Compile_Time_Constraint_Error
6731 (High_Bound (Ck_Node),
6732 "static value out of range of}?", T_Typ));
6734 else
6735 Add_Check
6736 (Compile_Time_Constraint_Error
6737 (Wnode,
6738 "static range out of bounds of}?", T_Typ));
6739 end if;
6740 end if;
6741 end if;
6743 else
6744 declare
6745 LB : Node_Id := Low_Bound (Ck_Node);
6746 HB : Node_Id := High_Bound (Ck_Node);
6748 begin
6749 -- If either bound is a discriminant and we are within the
6750 -- record declaration, it is a use of the discriminant in a
6751 -- constraint of a component, and nothing can be checked
6752 -- here. The check will be emitted within the init proc.
6753 -- Before then, the discriminal has no real meaning.
6754 -- Similarly, if the entity is a discriminal, there is no
6755 -- check to perform yet.
6757 -- The same holds within a discriminated synchronized type,
6758 -- where the discriminant may constrain a component or an
6759 -- entry family.
6761 if Nkind (LB) = N_Identifier
6762 and then Denotes_Discriminant (LB, True)
6763 then
6764 if Current_Scope = Scope (Entity (LB))
6765 or else Is_Concurrent_Type (Current_Scope)
6766 or else Ekind (Entity (LB)) /= E_Discriminant
6767 then
6768 return Ret_Result;
6769 else
6770 LB :=
6771 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6772 end if;
6773 end if;
6775 if Nkind (HB) = N_Identifier
6776 and then Denotes_Discriminant (HB, True)
6777 then
6778 if Current_Scope = Scope (Entity (HB))
6779 or else Is_Concurrent_Type (Current_Scope)
6780 or else Ekind (Entity (HB)) /= E_Discriminant
6781 then
6782 return Ret_Result;
6783 else
6784 HB :=
6785 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6786 end if;
6787 end if;
6789 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6790 Set_Paren_Count (Cond, 1);
6792 Cond :=
6793 Make_And_Then (Loc,
6794 Left_Opnd =>
6795 Make_Op_Ge (Loc,
6796 Left_Opnd => Duplicate_Subexpr_No_Checks (HB),
6797 Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6798 Right_Opnd => Cond);
6799 end;
6800 end if;
6801 end;
6803 elsif Is_Scalar_Type (S_Typ) then
6805 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
6806 -- except the above simply sets a flag in the node and lets
6807 -- gigi generate the check base on the Etype of the expression.
6808 -- Sometimes, however we want to do a dynamic check against an
6809 -- arbitrary target type, so we do that here.
6811 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6812 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6814 -- For literals, we can tell if the constraint error will be
6815 -- raised at compile time, so we never need a dynamic check, but
6816 -- if the exception will be raised, then post the usual warning,
6817 -- and replace the literal with a raise constraint error
6818 -- expression. As usual, skip this for access types
6820 elsif Compile_Time_Known_Value (Ck_Node)
6821 and then not Do_Access
6822 then
6823 declare
6824 LB : constant Node_Id := Type_Low_Bound (T_Typ);
6825 UB : constant Node_Id := Type_High_Bound (T_Typ);
6827 Out_Of_Range : Boolean;
6828 Static_Bounds : constant Boolean :=
6829 Compile_Time_Known_Value (LB)
6830 and Compile_Time_Known_Value (UB);
6832 begin
6833 -- Following range tests should use Sem_Eval routine ???
6835 if Static_Bounds then
6836 if Is_Floating_Point_Type (S_Typ) then
6837 Out_Of_Range :=
6838 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6839 or else
6840 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6842 -- Fixed or discrete type
6844 else
6845 Out_Of_Range :=
6846 Expr_Value (Ck_Node) < Expr_Value (LB)
6847 or else
6848 Expr_Value (Ck_Node) > Expr_Value (UB);
6849 end if;
6851 -- Bounds of the type are static and the literal is out of
6852 -- range so output a warning message.
6854 if Out_Of_Range then
6855 if No (Warn_Node) then
6856 Add_Check
6857 (Compile_Time_Constraint_Error
6858 (Ck_Node,
6859 "static value out of range of}?", T_Typ));
6861 else
6862 Add_Check
6863 (Compile_Time_Constraint_Error
6864 (Wnode,
6865 "static value out of range of}?", T_Typ));
6866 end if;
6867 end if;
6869 else
6870 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6871 end if;
6872 end;
6874 -- Here for the case of a non-static expression, we need a runtime
6875 -- check unless the source type range is guaranteed to be in the
6876 -- range of the target type.
6878 else
6879 if not In_Subrange_Of (S_Typ, T_Typ) then
6880 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6881 end if;
6882 end if;
6883 end if;
6885 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6886 if Is_Constrained (T_Typ) then
6888 Expr_Actual := Get_Referenced_Object (Ck_Node);
6889 Exptyp := Get_Actual_Subtype (Expr_Actual);
6891 if Is_Access_Type (Exptyp) then
6892 Exptyp := Designated_Type (Exptyp);
6893 end if;
6895 -- String_Literal case. This needs to be handled specially be-
6896 -- cause no index types are available for string literals. The
6897 -- condition is simply:
6899 -- T_Typ'Length = string-literal-length
6901 if Nkind (Expr_Actual) = N_String_Literal then
6902 null;
6904 -- General array case. Here we have a usable actual subtype for
6905 -- the expression, and the condition is built from the two types
6907 -- T_Typ'First < Exptyp'First or else
6908 -- T_Typ'Last > Exptyp'Last or else
6909 -- T_Typ'First(1) < Exptyp'First(1) or else
6910 -- T_Typ'Last(1) > Exptyp'Last(1) or else
6911 -- ...
6913 elsif Is_Constrained (Exptyp) then
6914 declare
6915 Ndims : constant Nat := Number_Dimensions (T_Typ);
6917 L_Index : Node_Id;
6918 R_Index : Node_Id;
6920 begin
6921 L_Index := First_Index (T_Typ);
6922 R_Index := First_Index (Exptyp);
6924 for Indx in 1 .. Ndims loop
6925 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6926 or else
6927 Nkind (R_Index) = N_Raise_Constraint_Error)
6928 then
6929 -- Deal with compile time length check. Note that we
6930 -- skip this in the access case, because the access
6931 -- value may be null, so we cannot know statically.
6933 if not
6934 Subtypes_Statically_Match
6935 (Etype (L_Index), Etype (R_Index))
6936 then
6937 -- If the target type is constrained then we
6938 -- have to check for exact equality of bounds
6939 -- (required for qualified expressions).
6941 if Is_Constrained (T_Typ) then
6942 Evolve_Or_Else
6943 (Cond,
6944 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6945 else
6946 Evolve_Or_Else
6947 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6948 end if;
6949 end if;
6951 Next (L_Index);
6952 Next (R_Index);
6953 end if;
6954 end loop;
6955 end;
6957 -- Handle cases where we do not get a usable actual subtype that
6958 -- is constrained. This happens for example in the function call
6959 -- and explicit dereference cases. In these cases, we have to get
6960 -- the length or range from the expression itself, making sure we
6961 -- do not evaluate it more than once.
6963 -- Here Ck_Node is the original expression, or more properly the
6964 -- result of applying Duplicate_Expr to the original tree,
6965 -- forcing the result to be a name.
6967 else
6968 declare
6969 Ndims : constant Nat := Number_Dimensions (T_Typ);
6971 begin
6972 -- Build the condition for the explicit dereference case
6974 for Indx in 1 .. Ndims loop
6975 Evolve_Or_Else
6976 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
6977 end loop;
6978 end;
6979 end if;
6981 else
6982 -- For a conversion to an unconstrained array type, generate an
6983 -- Action to check that the bounds of the source value are within
6984 -- the constraints imposed by the target type (RM 4.6(38)). No
6985 -- check is needed for a conversion to an access to unconstrained
6986 -- array type, as 4.6(24.15/2) requires the designated subtypes
6987 -- of the two access types to statically match.
6989 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
6990 and then not Do_Access
6991 then
6992 declare
6993 Opnd_Index : Node_Id;
6994 Targ_Index : Node_Id;
6995 Opnd_Range : Node_Id;
6997 begin
6998 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
6999 Targ_Index := First_Index (T_Typ);
7000 while Present (Opnd_Index) loop
7002 -- If the index is a range, use its bounds. If it is an
7003 -- entity (as will be the case if it is a named subtype
7004 -- or an itype created for a slice) retrieve its range.
7006 if Is_Entity_Name (Opnd_Index)
7007 and then Is_Type (Entity (Opnd_Index))
7008 then
7009 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
7010 else
7011 Opnd_Range := Opnd_Index;
7012 end if;
7014 if Nkind (Opnd_Range) = N_Range then
7015 if Is_In_Range
7016 (Low_Bound (Opnd_Range), Etype (Targ_Index),
7017 Assume_Valid => True)
7018 and then
7019 Is_In_Range
7020 (High_Bound (Opnd_Range), Etype (Targ_Index),
7021 Assume_Valid => True)
7022 then
7023 null;
7025 -- If null range, no check needed
7027 elsif
7028 Compile_Time_Known_Value (High_Bound (Opnd_Range))
7029 and then
7030 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
7031 and then
7032 Expr_Value (High_Bound (Opnd_Range)) <
7033 Expr_Value (Low_Bound (Opnd_Range))
7034 then
7035 null;
7037 elsif Is_Out_Of_Range
7038 (Low_Bound (Opnd_Range), Etype (Targ_Index),
7039 Assume_Valid => True)
7040 or else
7041 Is_Out_Of_Range
7042 (High_Bound (Opnd_Range), Etype (Targ_Index),
7043 Assume_Valid => True)
7044 then
7045 Add_Check
7046 (Compile_Time_Constraint_Error
7047 (Wnode, "value out of range of}?", T_Typ));
7049 else
7050 Evolve_Or_Else
7051 (Cond,
7052 Discrete_Range_Cond
7053 (Opnd_Range, Etype (Targ_Index)));
7054 end if;
7055 end if;
7057 Next_Index (Opnd_Index);
7058 Next_Index (Targ_Index);
7059 end loop;
7060 end;
7061 end if;
7062 end if;
7063 end if;
7065 -- Construct the test and insert into the tree
7067 if Present (Cond) then
7068 if Do_Access then
7069 Cond := Guard_Access (Cond, Loc, Ck_Node);
7070 end if;
7072 Add_Check
7073 (Make_Raise_Constraint_Error (Loc,
7074 Condition => Cond,
7075 Reason => CE_Range_Check_Failed));
7076 end if;
7078 return Ret_Result;
7079 end Selected_Range_Checks;
7081 -------------------------------
7082 -- Storage_Checks_Suppressed --
7083 -------------------------------
7085 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
7086 begin
7087 if Present (E) and then Checks_May_Be_Suppressed (E) then
7088 return Is_Check_Suppressed (E, Storage_Check);
7089 else
7090 return Scope_Suppress (Storage_Check);
7091 end if;
7092 end Storage_Checks_Suppressed;
7094 ---------------------------
7095 -- Tag_Checks_Suppressed --
7096 ---------------------------
7098 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
7099 begin
7100 if Present (E) then
7101 if Kill_Tag_Checks (E) then
7102 return True;
7103 elsif Checks_May_Be_Suppressed (E) then
7104 return Is_Check_Suppressed (E, Tag_Check);
7105 end if;
7106 end if;
7108 return Scope_Suppress (Tag_Check);
7109 end Tag_Checks_Suppressed;
7111 --------------------------
7112 -- Validity_Check_Range --
7113 --------------------------
7115 procedure Validity_Check_Range (N : Node_Id) is
7116 begin
7117 if Validity_Checks_On and Validity_Check_Operands then
7118 if Nkind (N) = N_Range then
7119 Ensure_Valid (Low_Bound (N));
7120 Ensure_Valid (High_Bound (N));
7121 end if;
7122 end if;
7123 end Validity_Check_Range;
7125 --------------------------------
7126 -- Validity_Checks_Suppressed --
7127 --------------------------------
7129 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
7130 begin
7131 if Present (E) and then Checks_May_Be_Suppressed (E) then
7132 return Is_Check_Suppressed (E, Validity_Check);
7133 else
7134 return Scope_Suppress (Validity_Check);
7135 end if;
7136 end Validity_Checks_Suppressed;
7138 end Checks;