Merge from mainline (168000:168310).
[official-gcc/graphite-test-results.git] / gcc / ada / checks.adb
blob46a966827fccb78d4702a8604679b7f3928ce327
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 principally 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 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. Strictly we don't
654 -- have to do anything, since if the alignment is bad, we have an
655 -- erroneous program. However we are allowed to check for erroneous
656 -- conditions and we decide to do this by default if the check is not
657 -- suppressed.
659 -- However, don't do the check if elaboration code is unwanted
661 if Restriction_Active (No_Elaboration_Code) then
662 return;
664 -- Generate a check to raise PE if alignment may be inappropriate
666 else
667 -- If the original expression is a non-static constant, use the
668 -- name of the constant itself rather than duplicating its
669 -- defining expression, which was extracted above.
671 -- Note: Expr is empty if the address-clause is applied to in-mode
672 -- actuals (allowed by 13.1(22)).
674 if not Present (Expr)
675 or else
676 (Is_Entity_Name (Expression (AC))
677 and then Ekind (Entity (Expression (AC))) = E_Constant
678 and then Nkind (Parent (Entity (Expression (AC))))
679 = N_Object_Declaration)
680 then
681 Expr := New_Copy_Tree (Expression (AC));
682 else
683 Remove_Side_Effects (Expr);
684 end if;
686 Insert_After_And_Analyze (N,
687 Make_Raise_Program_Error (Loc,
688 Condition =>
689 Make_Op_Ne (Loc,
690 Left_Opnd =>
691 Make_Op_Mod (Loc,
692 Left_Opnd =>
693 Unchecked_Convert_To
694 (RTE (RE_Integer_Address), Expr),
695 Right_Opnd =>
696 Make_Attribute_Reference (Loc,
697 Prefix => New_Occurrence_Of (E, Loc),
698 Attribute_Name => Name_Alignment)),
699 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
700 Reason => PE_Misaligned_Address_Value),
701 Suppress => All_Checks);
702 return;
703 end if;
705 exception
706 -- If we have some missing run time component in configurable run time
707 -- mode then just skip the check (it is not required in any case).
709 when RE_Not_Available =>
710 return;
711 end Apply_Address_Clause_Check;
713 -------------------------------------
714 -- Apply_Arithmetic_Overflow_Check --
715 -------------------------------------
717 -- This routine is called only if the type is an integer type, and a
718 -- software arithmetic overflow check may be needed for op (add, subtract,
719 -- or multiply). This check is performed only if Software_Overflow_Checking
720 -- is enabled and Do_Overflow_Check is set. In this case we expand the
721 -- operation into a more complex sequence of tests that ensures that
722 -- overflow is properly caught.
724 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
725 Loc : constant Source_Ptr := Sloc (N);
726 Typ : constant Entity_Id := Etype (N);
727 Rtyp : constant Entity_Id := Root_Type (Typ);
729 begin
730 -- An interesting special case. If the arithmetic operation appears as
731 -- the operand of a type conversion:
733 -- type1 (x op y)
735 -- and all the following conditions apply:
737 -- arithmetic operation is for a signed integer type
738 -- target type type1 is a static integer subtype
739 -- range of x and y are both included in the range of type1
740 -- range of x op y is included in the range of type1
741 -- size of type1 is at least twice the result size of op
743 -- then we don't do an overflow check in any case, instead we transform
744 -- the operation so that we end up with:
746 -- type1 (type1 (x) op type1 (y))
748 -- This avoids intermediate overflow before the conversion. It is
749 -- explicitly permitted by RM 3.5.4(24):
751 -- For the execution of a predefined operation of a signed integer
752 -- type, the implementation need not raise Constraint_Error if the
753 -- result is outside the base range of the type, so long as the
754 -- correct result is produced.
756 -- It's hard to imagine that any programmer counts on the exception
757 -- being raised in this case, and in any case it's wrong coding to
758 -- have this expectation, given the RM permission. Furthermore, other
759 -- Ada compilers do allow such out of range results.
761 -- Note that we do this transformation even if overflow checking is
762 -- off, since this is precisely about giving the "right" result and
763 -- avoiding the need for an overflow check.
765 -- Note: this circuit is partially redundant with respect to the similar
766 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
767 -- with cases that do not come through here. We still need the following
768 -- processing even with the Exp_Ch4 code in place, since we want to be
769 -- sure not to generate the arithmetic overflow check in these cases
770 -- (Exp_Ch4 would have a hard time removing them once generated).
772 if Is_Signed_Integer_Type (Typ)
773 and then Nkind (Parent (N)) = N_Type_Conversion
774 then
775 declare
776 Target_Type : constant Entity_Id :=
777 Base_Type (Entity (Subtype_Mark (Parent (N))));
779 Llo, Lhi : Uint;
780 Rlo, Rhi : Uint;
781 LOK, ROK : Boolean;
783 Vlo : Uint;
784 Vhi : Uint;
785 VOK : Boolean;
787 Tlo : Uint;
788 Thi : Uint;
790 begin
791 if Is_Integer_Type (Target_Type)
792 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
793 then
794 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
795 Thi := Expr_Value (Type_High_Bound (Target_Type));
797 Determine_Range
798 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
799 Determine_Range
800 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
802 if (LOK and ROK)
803 and then Tlo <= Llo and then Lhi <= Thi
804 and then Tlo <= Rlo and then Rhi <= Thi
805 then
806 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
808 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
809 Rewrite (Left_Opnd (N),
810 Make_Type_Conversion (Loc,
811 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
812 Expression => Relocate_Node (Left_Opnd (N))));
814 Rewrite (Right_Opnd (N),
815 Make_Type_Conversion (Loc,
816 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
817 Expression => Relocate_Node (Right_Opnd (N))));
819 -- Rewrite the conversion operand so that the original
820 -- node is retained, in order to avoid the warning for
821 -- redundant conversions in Resolve_Type_Conversion.
823 Rewrite (N, Relocate_Node (N));
825 Set_Etype (N, Target_Type);
827 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
828 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
830 -- Given that the target type is twice the size of the
831 -- source type, overflow is now impossible, so we can
832 -- safely kill the overflow check and return.
834 Set_Do_Overflow_Check (N, False);
835 return;
836 end if;
837 end if;
838 end if;
839 end;
840 end if;
842 -- Now see if an overflow check is required
844 declare
845 Siz : constant Int := UI_To_Int (Esize (Rtyp));
846 Dsiz : constant Int := Siz * 2;
847 Opnod : Node_Id;
848 Ctyp : Entity_Id;
849 Opnd : Node_Id;
850 Cent : RE_Id;
852 begin
853 -- Skip check if back end does overflow checks, or the overflow flag
854 -- is not set anyway, or we are not doing code expansion, or the
855 -- parent node is a type conversion whose operand is an arithmetic
856 -- operation on signed integers on which the expander can promote
857 -- later the operands to type Integer (see Expand_N_Type_Conversion).
859 -- Special case CLI target, where arithmetic overflow checks can be
860 -- performed for integer and long_integer
862 if Backend_Overflow_Checks_On_Target
863 or else not Do_Overflow_Check (N)
864 or else not Expander_Active
865 or else (Present (Parent (N))
866 and then Nkind (Parent (N)) = N_Type_Conversion
867 and then Integer_Promotion_Possible (Parent (N)))
868 or else
869 (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
870 then
871 return;
872 end if;
874 -- Otherwise, generate the full general code for front end overflow
875 -- detection, which works by doing arithmetic in a larger type:
877 -- x op y
879 -- is expanded into
881 -- Typ (Checktyp (x) op Checktyp (y));
883 -- where Typ is the type of the original expression, and Checktyp is
884 -- an integer type of sufficient length to hold the largest possible
885 -- result.
887 -- If the size of check type exceeds the size of Long_Long_Integer,
888 -- we use a different approach, expanding to:
890 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
892 -- where xxx is Add, Multiply or Subtract as appropriate
894 -- Find check type if one exists
896 if Dsiz <= Standard_Integer_Size then
897 Ctyp := Standard_Integer;
899 elsif Dsiz <= Standard_Long_Long_Integer_Size then
900 Ctyp := Standard_Long_Long_Integer;
902 -- No check type exists, use runtime call
904 else
905 if Nkind (N) = N_Op_Add then
906 Cent := RE_Add_With_Ovflo_Check;
908 elsif Nkind (N) = N_Op_Multiply then
909 Cent := RE_Multiply_With_Ovflo_Check;
911 else
912 pragma Assert (Nkind (N) = N_Op_Subtract);
913 Cent := RE_Subtract_With_Ovflo_Check;
914 end if;
916 Rewrite (N,
917 OK_Convert_To (Typ,
918 Make_Function_Call (Loc,
919 Name => New_Reference_To (RTE (Cent), Loc),
920 Parameter_Associations => New_List (
921 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
922 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
924 Analyze_And_Resolve (N, Typ);
925 return;
926 end if;
928 -- If we fall through, we have the case where we do the arithmetic
929 -- in the next higher type and get the check by conversion. In these
930 -- cases Ctyp is set to the type to be used as the check type.
932 Opnod := Relocate_Node (N);
934 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
936 Analyze (Opnd);
937 Set_Etype (Opnd, Ctyp);
938 Set_Analyzed (Opnd, True);
939 Set_Left_Opnd (Opnod, Opnd);
941 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
943 Analyze (Opnd);
944 Set_Etype (Opnd, Ctyp);
945 Set_Analyzed (Opnd, True);
946 Set_Right_Opnd (Opnod, Opnd);
948 -- The type of the operation changes to the base type of the check
949 -- type, and we reset the overflow check indication, since clearly no
950 -- overflow is possible now that we are using a double length type.
951 -- We also set the Analyzed flag to avoid a recursive attempt to
952 -- expand the node.
954 Set_Etype (Opnod, Base_Type (Ctyp));
955 Set_Do_Overflow_Check (Opnod, False);
956 Set_Analyzed (Opnod, True);
958 -- Now build the outer conversion
960 Opnd := OK_Convert_To (Typ, Opnod);
961 Analyze (Opnd);
962 Set_Etype (Opnd, Typ);
964 -- In the discrete type case, we directly generate the range check
965 -- for the outer operand. This range check will implement the
966 -- required overflow check.
968 if Is_Discrete_Type (Typ) then
969 Rewrite (N, Opnd);
970 Generate_Range_Check
971 (Expression (N), Typ, CE_Overflow_Check_Failed);
973 -- For other types, we enable overflow checking on the conversion,
974 -- after setting the node as analyzed to prevent recursive attempts
975 -- to expand the conversion node.
977 else
978 Set_Analyzed (Opnd, True);
979 Enable_Overflow_Check (Opnd);
980 Rewrite (N, Opnd);
981 end if;
983 exception
984 when RE_Not_Available =>
985 return;
986 end;
987 end Apply_Arithmetic_Overflow_Check;
989 ----------------------------
990 -- Apply_Constraint_Check --
991 ----------------------------
993 procedure Apply_Constraint_Check
994 (N : Node_Id;
995 Typ : Entity_Id;
996 No_Sliding : Boolean := False)
998 Desig_Typ : Entity_Id;
1000 begin
1001 -- No checks inside a generic (check the instantiations)
1003 if Inside_A_Generic then
1004 return;
1005 end if;
1007 -- Apply required constraint checks
1009 if Is_Scalar_Type (Typ) then
1010 Apply_Scalar_Range_Check (N, Typ);
1012 elsif Is_Array_Type (Typ) then
1014 -- A useful optimization: an aggregate with only an others clause
1015 -- always has the right bounds.
1017 if Nkind (N) = N_Aggregate
1018 and then No (Expressions (N))
1019 and then Nkind
1020 (First (Choices (First (Component_Associations (N)))))
1021 = N_Others_Choice
1022 then
1023 return;
1024 end if;
1026 if Is_Constrained (Typ) then
1027 Apply_Length_Check (N, Typ);
1029 if No_Sliding then
1030 Apply_Range_Check (N, Typ);
1031 end if;
1032 else
1033 Apply_Range_Check (N, Typ);
1034 end if;
1036 elsif (Is_Record_Type (Typ)
1037 or else Is_Private_Type (Typ))
1038 and then Has_Discriminants (Base_Type (Typ))
1039 and then Is_Constrained (Typ)
1040 then
1041 Apply_Discriminant_Check (N, Typ);
1043 elsif Is_Access_Type (Typ) then
1045 Desig_Typ := Designated_Type (Typ);
1047 -- No checks necessary if expression statically null
1049 if Known_Null (N) then
1050 if Can_Never_Be_Null (Typ) then
1051 Install_Null_Excluding_Check (N);
1052 end if;
1054 -- No sliding possible on access to arrays
1056 elsif Is_Array_Type (Desig_Typ) then
1057 if Is_Constrained (Desig_Typ) then
1058 Apply_Length_Check (N, Typ);
1059 end if;
1061 Apply_Range_Check (N, Typ);
1063 elsif Has_Discriminants (Base_Type (Desig_Typ))
1064 and then Is_Constrained (Desig_Typ)
1065 then
1066 Apply_Discriminant_Check (N, Typ);
1067 end if;
1069 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1070 -- this check if the constraint node is illegal, as shown by having
1071 -- an error posted. This additional guard prevents cascaded errors
1072 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1074 if Can_Never_Be_Null (Typ)
1075 and then not Can_Never_Be_Null (Etype (N))
1076 and then not Error_Posted (N)
1077 then
1078 Install_Null_Excluding_Check (N);
1079 end if;
1080 end if;
1081 end Apply_Constraint_Check;
1083 ------------------------------
1084 -- Apply_Discriminant_Check --
1085 ------------------------------
1087 procedure Apply_Discriminant_Check
1088 (N : Node_Id;
1089 Typ : Entity_Id;
1090 Lhs : Node_Id := Empty)
1092 Loc : constant Source_Ptr := Sloc (N);
1093 Do_Access : constant Boolean := Is_Access_Type (Typ);
1094 S_Typ : Entity_Id := Etype (N);
1095 Cond : Node_Id;
1096 T_Typ : Entity_Id;
1098 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1099 -- A heap object with an indefinite subtype is constrained by its
1100 -- initial value, and assigning to it requires a constraint_check.
1101 -- The target may be an explicit dereference, or a renaming of one.
1103 function Is_Aliased_Unconstrained_Component return Boolean;
1104 -- It is possible for an aliased component to have a nominal
1105 -- unconstrained subtype (through instantiation). If this is a
1106 -- discriminated component assigned in the expansion of an aggregate
1107 -- in an initialization, the check must be suppressed. This unusual
1108 -- situation requires a predicate of its own.
1110 ----------------------------------
1111 -- Denotes_Explicit_Dereference --
1112 ----------------------------------
1114 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1115 begin
1116 return
1117 Nkind (Obj) = N_Explicit_Dereference
1118 or else
1119 (Is_Entity_Name (Obj)
1120 and then Present (Renamed_Object (Entity (Obj)))
1121 and then Nkind (Renamed_Object (Entity (Obj))) =
1122 N_Explicit_Dereference);
1123 end Denotes_Explicit_Dereference;
1125 ----------------------------------------
1126 -- Is_Aliased_Unconstrained_Component --
1127 ----------------------------------------
1129 function Is_Aliased_Unconstrained_Component return Boolean is
1130 Comp : Entity_Id;
1131 Pref : Node_Id;
1133 begin
1134 if Nkind (Lhs) /= N_Selected_Component then
1135 return False;
1136 else
1137 Comp := Entity (Selector_Name (Lhs));
1138 Pref := Prefix (Lhs);
1139 end if;
1141 if Ekind (Comp) /= E_Component
1142 or else not Is_Aliased (Comp)
1143 then
1144 return False;
1145 end if;
1147 return not Comes_From_Source (Pref)
1148 and then In_Instance
1149 and then not Is_Constrained (Etype (Comp));
1150 end Is_Aliased_Unconstrained_Component;
1152 -- Start of processing for Apply_Discriminant_Check
1154 begin
1155 if Do_Access then
1156 T_Typ := Designated_Type (Typ);
1157 else
1158 T_Typ := Typ;
1159 end if;
1161 -- Nothing to do if discriminant checks are suppressed or else no code
1162 -- is to be generated
1164 if not Expander_Active
1165 or else Discriminant_Checks_Suppressed (T_Typ)
1166 then
1167 return;
1168 end if;
1170 -- No discriminant checks necessary for an access when expression is
1171 -- statically Null. This is not only an optimization, it is fundamental
1172 -- because otherwise discriminant checks may be generated in init procs
1173 -- for types containing an access to a not-yet-frozen record, causing a
1174 -- deadly forward reference.
1176 -- Also, if the expression is of an access type whose designated type is
1177 -- incomplete, then the access value must be null and we suppress the
1178 -- check.
1180 if Known_Null (N) then
1181 return;
1183 elsif Is_Access_Type (S_Typ) then
1184 S_Typ := Designated_Type (S_Typ);
1186 if Ekind (S_Typ) = E_Incomplete_Type then
1187 return;
1188 end if;
1189 end if;
1191 -- If an assignment target is present, then we need to generate the
1192 -- actual subtype if the target is a parameter or aliased object with
1193 -- an unconstrained nominal subtype.
1195 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1196 -- subtype to the parameter and dereference cases, since other aliased
1197 -- objects are unconstrained (unless the nominal subtype is explicitly
1198 -- constrained).
1200 if Present (Lhs)
1201 and then (Present (Param_Entity (Lhs))
1202 or else (Ada_Version < Ada_2005
1203 and then not Is_Constrained (T_Typ)
1204 and then Is_Aliased_View (Lhs)
1205 and then not Is_Aliased_Unconstrained_Component)
1206 or else (Ada_Version >= Ada_2005
1207 and then not Is_Constrained (T_Typ)
1208 and then Denotes_Explicit_Dereference (Lhs)
1209 and then Nkind (Original_Node (Lhs)) /=
1210 N_Function_Call))
1211 then
1212 T_Typ := Get_Actual_Subtype (Lhs);
1213 end if;
1215 -- Nothing to do if the type is unconstrained (this is the case where
1216 -- the actual subtype in the RM sense of N is unconstrained and no check
1217 -- is required).
1219 if not Is_Constrained (T_Typ) then
1220 return;
1222 -- Ada 2005: nothing to do if the type is one for which there is a
1223 -- partial view that is constrained.
1225 elsif Ada_Version >= Ada_2005
1226 and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1227 then
1228 return;
1229 end if;
1231 -- Nothing to do if the type is an Unchecked_Union
1233 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1234 return;
1235 end if;
1237 -- Suppress checks if the subtypes are the same. the check must be
1238 -- preserved in an assignment to a formal, because the constraint is
1239 -- given by the actual.
1241 if Nkind (Original_Node (N)) /= N_Allocator
1242 and then (No (Lhs)
1243 or else not Is_Entity_Name (Lhs)
1244 or else No (Param_Entity (Lhs)))
1245 then
1246 if (Etype (N) = Typ
1247 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1248 and then not Is_Aliased_View (Lhs)
1249 then
1250 return;
1251 end if;
1253 -- We can also eliminate checks on allocators with a subtype mark that
1254 -- coincides with the context type. The context type may be a subtype
1255 -- without a constraint (common case, a generic actual).
1257 elsif Nkind (Original_Node (N)) = N_Allocator
1258 and then Is_Entity_Name (Expression (Original_Node (N)))
1259 then
1260 declare
1261 Alloc_Typ : constant Entity_Id :=
1262 Entity (Expression (Original_Node (N)));
1264 begin
1265 if Alloc_Typ = T_Typ
1266 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1267 and then Is_Entity_Name (
1268 Subtype_Indication (Parent (T_Typ)))
1269 and then Alloc_Typ = Base_Type (T_Typ))
1271 then
1272 return;
1273 end if;
1274 end;
1275 end if;
1277 -- See if we have a case where the types are both constrained, and all
1278 -- the constraints are constants. In this case, we can do the check
1279 -- successfully at compile time.
1281 -- We skip this check for the case where the node is a rewritten`
1282 -- allocator, because it already carries the context subtype, and
1283 -- extracting the discriminants from the aggregate is messy.
1285 if Is_Constrained (S_Typ)
1286 and then Nkind (Original_Node (N)) /= N_Allocator
1287 then
1288 declare
1289 DconT : Elmt_Id;
1290 Discr : Entity_Id;
1291 DconS : Elmt_Id;
1292 ItemS : Node_Id;
1293 ItemT : Node_Id;
1295 begin
1296 -- S_Typ may not have discriminants in the case where it is a
1297 -- private type completed by a default discriminated type. In that
1298 -- case, we need to get the constraints from the underlying_type.
1299 -- If the underlying type is unconstrained (i.e. has no default
1300 -- discriminants) no check is needed.
1302 if Has_Discriminants (S_Typ) then
1303 Discr := First_Discriminant (S_Typ);
1304 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1306 else
1307 Discr := First_Discriminant (Underlying_Type (S_Typ));
1308 DconS :=
1309 First_Elmt
1310 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1312 if No (DconS) then
1313 return;
1314 end if;
1316 -- A further optimization: if T_Typ is derived from S_Typ
1317 -- without imposing a constraint, no check is needed.
1319 if Nkind (Original_Node (Parent (T_Typ))) =
1320 N_Full_Type_Declaration
1321 then
1322 declare
1323 Type_Def : constant Node_Id :=
1324 Type_Definition
1325 (Original_Node (Parent (T_Typ)));
1326 begin
1327 if Nkind (Type_Def) = N_Derived_Type_Definition
1328 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1329 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1330 then
1331 return;
1332 end if;
1333 end;
1334 end if;
1335 end if;
1337 DconT := First_Elmt (Discriminant_Constraint (T_Typ));
1339 while Present (Discr) loop
1340 ItemS := Node (DconS);
1341 ItemT := Node (DconT);
1343 -- For a discriminated component type constrained by the
1344 -- current instance of an enclosing type, there is no
1345 -- applicable discriminant check.
1347 if Nkind (ItemT) = N_Attribute_Reference
1348 and then Is_Access_Type (Etype (ItemT))
1349 and then Is_Entity_Name (Prefix (ItemT))
1350 and then Is_Type (Entity (Prefix (ItemT)))
1351 then
1352 return;
1353 end if;
1355 -- If the expressions for the discriminants are identical
1356 -- and it is side-effect free (for now just an entity),
1357 -- this may be a shared constraint, e.g. from a subtype
1358 -- without a constraint introduced as a generic actual.
1359 -- Examine other discriminants if any.
1361 if ItemS = ItemT
1362 and then Is_Entity_Name (ItemS)
1363 then
1364 null;
1366 elsif not Is_OK_Static_Expression (ItemS)
1367 or else not Is_OK_Static_Expression (ItemT)
1368 then
1369 exit;
1371 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1372 if Do_Access then -- needs run-time check.
1373 exit;
1374 else
1375 Apply_Compile_Time_Constraint_Error
1376 (N, "incorrect value for discriminant&?",
1377 CE_Discriminant_Check_Failed, Ent => Discr);
1378 return;
1379 end if;
1380 end if;
1382 Next_Elmt (DconS);
1383 Next_Elmt (DconT);
1384 Next_Discriminant (Discr);
1385 end loop;
1387 if No (Discr) then
1388 return;
1389 end if;
1390 end;
1391 end if;
1393 -- Here we need a discriminant check. First build the expression
1394 -- for the comparisons of the discriminants:
1396 -- (n.disc1 /= typ.disc1) or else
1397 -- (n.disc2 /= typ.disc2) or else
1398 -- ...
1399 -- (n.discn /= typ.discn)
1401 Cond := Build_Discriminant_Checks (N, T_Typ);
1403 -- If Lhs is set and is a parameter, then the condition is
1404 -- guarded by: lhs'constrained and then (condition built above)
1406 if Present (Param_Entity (Lhs)) then
1407 Cond :=
1408 Make_And_Then (Loc,
1409 Left_Opnd =>
1410 Make_Attribute_Reference (Loc,
1411 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1412 Attribute_Name => Name_Constrained),
1413 Right_Opnd => Cond);
1414 end if;
1416 if Do_Access then
1417 Cond := Guard_Access (Cond, Loc, N);
1418 end if;
1420 Insert_Action (N,
1421 Make_Raise_Constraint_Error (Loc,
1422 Condition => Cond,
1423 Reason => CE_Discriminant_Check_Failed));
1424 end Apply_Discriminant_Check;
1426 ------------------------
1427 -- Apply_Divide_Check --
1428 ------------------------
1430 procedure Apply_Divide_Check (N : Node_Id) is
1431 Loc : constant Source_Ptr := Sloc (N);
1432 Typ : constant Entity_Id := Etype (N);
1433 Left : constant Node_Id := Left_Opnd (N);
1434 Right : constant Node_Id := Right_Opnd (N);
1436 LLB : Uint;
1437 Llo : Uint;
1438 Lhi : Uint;
1439 LOK : Boolean;
1440 Rlo : Uint;
1441 Rhi : Uint;
1442 ROK : Boolean;
1444 pragma Warnings (Off, Lhi);
1445 -- Don't actually use this value
1447 begin
1448 if Expander_Active
1449 and then not Backend_Divide_Checks_On_Target
1450 and then Check_Needed (Right, Division_Check)
1451 then
1452 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1454 -- See if division by zero possible, and if so generate test. This
1455 -- part of the test is not controlled by the -gnato switch.
1457 if Do_Division_Check (N) then
1458 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1459 Insert_Action (N,
1460 Make_Raise_Constraint_Error (Loc,
1461 Condition =>
1462 Make_Op_Eq (Loc,
1463 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1464 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1465 Reason => CE_Divide_By_Zero));
1466 end if;
1467 end if;
1469 -- Test for extremely annoying case of xxx'First divided by -1
1471 if Do_Overflow_Check (N) then
1472 if Nkind (N) = N_Op_Divide
1473 and then Is_Signed_Integer_Type (Typ)
1474 then
1475 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1476 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1478 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1479 and then
1480 ((not LOK) or else (Llo = LLB))
1481 then
1482 Insert_Action (N,
1483 Make_Raise_Constraint_Error (Loc,
1484 Condition =>
1485 Make_And_Then (Loc,
1487 Make_Op_Eq (Loc,
1488 Left_Opnd =>
1489 Duplicate_Subexpr_Move_Checks (Left),
1490 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1492 Make_Op_Eq (Loc,
1493 Left_Opnd =>
1494 Duplicate_Subexpr (Right),
1495 Right_Opnd =>
1496 Make_Integer_Literal (Loc, -1))),
1497 Reason => CE_Overflow_Check_Failed));
1498 end if;
1499 end if;
1500 end if;
1501 end if;
1502 end Apply_Divide_Check;
1504 ----------------------------------
1505 -- Apply_Float_Conversion_Check --
1506 ----------------------------------
1508 -- Let F and I be the source and target types of the conversion. The RM
1509 -- specifies that a floating-point value X is rounded to the nearest
1510 -- integer, with halfway cases being rounded away from zero. The rounded
1511 -- value of X is checked against I'Range.
1513 -- The catch in the above paragraph is that there is no good way to know
1514 -- whether the round-to-integer operation resulted in overflow. A remedy is
1515 -- to perform a range check in the floating-point domain instead, however:
1517 -- (1) The bounds may not be known at compile time
1518 -- (2) The check must take into account rounding or truncation.
1519 -- (3) The range of type I may not be exactly representable in F.
1520 -- (4) For the rounding case, The end-points I'First - 0.5 and
1521 -- I'Last + 0.5 may or may not be in range, depending on the
1522 -- sign of I'First and I'Last.
1523 -- (5) X may be a NaN, which will fail any comparison
1525 -- The following steps correctly convert X with rounding:
1527 -- (1) If either I'First or I'Last is not known at compile time, use
1528 -- I'Base instead of I in the next three steps and perform a
1529 -- regular range check against I'Range after conversion.
1530 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1531 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1532 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1533 -- In other words, take one of the closest floating-point numbers
1534 -- (which is an integer value) to I'First, and see if it is in
1535 -- range or not.
1536 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1537 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1538 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1539 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1540 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1542 -- For the truncating case, replace steps (2) and (3) as follows:
1543 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1544 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1545 -- Lo_OK be True.
1546 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1547 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1548 -- Hi_OK be False
1550 procedure Apply_Float_Conversion_Check
1551 (Ck_Node : Node_Id;
1552 Target_Typ : Entity_Id)
1554 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1555 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1556 Loc : constant Source_Ptr := Sloc (Ck_Node);
1557 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1558 Target_Base : constant Entity_Id :=
1559 Implementation_Base_Type (Target_Typ);
1561 Par : constant Node_Id := Parent (Ck_Node);
1562 pragma Assert (Nkind (Par) = N_Type_Conversion);
1563 -- Parent of check node, must be a type conversion
1565 Truncate : constant Boolean := Float_Truncate (Par);
1566 Max_Bound : constant Uint :=
1567 UI_Expon
1568 (Machine_Radix_Value (Expr_Type),
1569 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
1571 -- Largest bound, so bound plus or minus half is a machine number of F
1573 Ifirst, Ilast : Uint;
1574 -- Bounds of integer type
1576 Lo, Hi : Ureal;
1577 -- Bounds to check in floating-point domain
1579 Lo_OK, Hi_OK : Boolean;
1580 -- True iff Lo resp. Hi belongs to I'Range
1582 Lo_Chk, Hi_Chk : Node_Id;
1583 -- Expressions that are False iff check fails
1585 Reason : RT_Exception_Code;
1587 begin
1588 if not Compile_Time_Known_Value (LB)
1589 or not Compile_Time_Known_Value (HB)
1590 then
1591 declare
1592 -- First check that the value falls in the range of the base type,
1593 -- to prevent overflow during conversion and then perform a
1594 -- regular range check against the (dynamic) bounds.
1596 pragma Assert (Target_Base /= Target_Typ);
1598 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
1600 begin
1601 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1602 Set_Etype (Temp, Target_Base);
1604 Insert_Action (Parent (Par),
1605 Make_Object_Declaration (Loc,
1606 Defining_Identifier => Temp,
1607 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1608 Expression => New_Copy_Tree (Par)),
1609 Suppress => All_Checks);
1611 Insert_Action (Par,
1612 Make_Raise_Constraint_Error (Loc,
1613 Condition =>
1614 Make_Not_In (Loc,
1615 Left_Opnd => New_Occurrence_Of (Temp, Loc),
1616 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1617 Reason => CE_Range_Check_Failed));
1618 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1620 return;
1621 end;
1622 end if;
1624 -- Get the (static) bounds of the target type
1626 Ifirst := Expr_Value (LB);
1627 Ilast := Expr_Value (HB);
1629 -- A simple optimization: if the expression is a universal literal,
1630 -- we can do the comparison with the bounds and the conversion to
1631 -- an integer type statically. The range checks are unchanged.
1633 if Nkind (Ck_Node) = N_Real_Literal
1634 and then Etype (Ck_Node) = Universal_Real
1635 and then Is_Integer_Type (Target_Typ)
1636 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
1637 then
1638 declare
1639 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
1641 begin
1642 if Int_Val <= Ilast and then Int_Val >= Ifirst then
1644 -- Conversion is safe
1646 Rewrite (Parent (Ck_Node),
1647 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
1648 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
1649 return;
1650 end if;
1651 end;
1652 end if;
1654 -- Check against lower bound
1656 if Truncate and then Ifirst > 0 then
1657 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1658 Lo_OK := False;
1660 elsif Truncate then
1661 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1662 Lo_OK := True;
1664 elsif abs (Ifirst) < Max_Bound then
1665 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1666 Lo_OK := (Ifirst > 0);
1668 else
1669 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1670 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1671 end if;
1673 if Lo_OK then
1675 -- Lo_Chk := (X >= Lo)
1677 Lo_Chk := Make_Op_Ge (Loc,
1678 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1679 Right_Opnd => Make_Real_Literal (Loc, Lo));
1681 else
1682 -- Lo_Chk := (X > Lo)
1684 Lo_Chk := Make_Op_Gt (Loc,
1685 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1686 Right_Opnd => Make_Real_Literal (Loc, Lo));
1687 end if;
1689 -- Check against higher bound
1691 if Truncate and then Ilast < 0 then
1692 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1693 Lo_OK := False;
1695 elsif Truncate then
1696 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1697 Hi_OK := True;
1699 elsif abs (Ilast) < Max_Bound then
1700 Hi := UR_From_Uint (Ilast) + Ureal_Half;
1701 Hi_OK := (Ilast < 0);
1702 else
1703 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1704 Hi_OK := (Hi <= UR_From_Uint (Ilast));
1705 end if;
1707 if Hi_OK then
1709 -- Hi_Chk := (X <= Hi)
1711 Hi_Chk := Make_Op_Le (Loc,
1712 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1713 Right_Opnd => Make_Real_Literal (Loc, Hi));
1715 else
1716 -- Hi_Chk := (X < Hi)
1718 Hi_Chk := Make_Op_Lt (Loc,
1719 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1720 Right_Opnd => Make_Real_Literal (Loc, Hi));
1721 end if;
1723 -- If the bounds of the target type are the same as those of the base
1724 -- type, the check is an overflow check as a range check is not
1725 -- performed in these cases.
1727 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1728 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1729 then
1730 Reason := CE_Overflow_Check_Failed;
1731 else
1732 Reason := CE_Range_Check_Failed;
1733 end if;
1735 -- Raise CE if either conditions does not hold
1737 Insert_Action (Ck_Node,
1738 Make_Raise_Constraint_Error (Loc,
1739 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1740 Reason => Reason));
1741 end Apply_Float_Conversion_Check;
1743 ------------------------
1744 -- Apply_Length_Check --
1745 ------------------------
1747 procedure Apply_Length_Check
1748 (Ck_Node : Node_Id;
1749 Target_Typ : Entity_Id;
1750 Source_Typ : Entity_Id := Empty)
1752 begin
1753 Apply_Selected_Length_Checks
1754 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1755 end Apply_Length_Check;
1757 ---------------------------
1758 -- Apply_Predicate_Check --
1759 ---------------------------
1761 procedure Apply_Predicate_Check (N : Node_Id; Typ : Entity_Id) is
1762 begin
1763 if Present (Predicate_Function (Typ)) then
1764 Insert_Action (N,
1765 Make_Predicate_Check (Typ, Duplicate_Subexpr (N)));
1766 end if;
1767 end Apply_Predicate_Check;
1769 -----------------------
1770 -- Apply_Range_Check --
1771 -----------------------
1773 procedure Apply_Range_Check
1774 (Ck_Node : Node_Id;
1775 Target_Typ : Entity_Id;
1776 Source_Typ : Entity_Id := Empty)
1778 begin
1779 Apply_Selected_Range_Checks
1780 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1781 end Apply_Range_Check;
1783 ------------------------------
1784 -- Apply_Scalar_Range_Check --
1785 ------------------------------
1787 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1788 -- off if it is already set on.
1790 procedure Apply_Scalar_Range_Check
1791 (Expr : Node_Id;
1792 Target_Typ : Entity_Id;
1793 Source_Typ : Entity_Id := Empty;
1794 Fixed_Int : Boolean := False)
1796 Parnt : constant Node_Id := Parent (Expr);
1797 S_Typ : Entity_Id;
1798 Arr : Node_Id := Empty; -- initialize to prevent warning
1799 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
1800 OK : Boolean;
1802 Is_Subscr_Ref : Boolean;
1803 -- Set true if Expr is a subscript
1805 Is_Unconstrained_Subscr_Ref : Boolean;
1806 -- Set true if Expr is a subscript of an unconstrained array. In this
1807 -- case we do not attempt to do an analysis of the value against the
1808 -- range of the subscript, since we don't know the actual subtype.
1810 Int_Real : Boolean;
1811 -- Set to True if Expr should be regarded as a real value even though
1812 -- the type of Expr might be discrete.
1814 procedure Bad_Value;
1815 -- Procedure called if value is determined to be out of range
1817 ---------------
1818 -- Bad_Value --
1819 ---------------
1821 procedure Bad_Value is
1822 begin
1823 Apply_Compile_Time_Constraint_Error
1824 (Expr, "value not in range of}?", CE_Range_Check_Failed,
1825 Ent => Target_Typ,
1826 Typ => Target_Typ);
1827 end Bad_Value;
1829 -- Start of processing for Apply_Scalar_Range_Check
1831 begin
1832 -- Return if check obviously not needed
1835 -- Not needed inside generic
1837 Inside_A_Generic
1839 -- Not needed if previous error
1841 or else Target_Typ = Any_Type
1842 or else Nkind (Expr) = N_Error
1844 -- Not needed for non-scalar type
1846 or else not Is_Scalar_Type (Target_Typ)
1848 -- Not needed if we know node raises CE already
1850 or else Raises_Constraint_Error (Expr)
1851 then
1852 return;
1853 end if;
1855 -- Now, see if checks are suppressed
1857 Is_Subscr_Ref :=
1858 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1860 if Is_Subscr_Ref then
1861 Arr := Prefix (Parnt);
1862 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1863 end if;
1865 if not Do_Range_Check (Expr) then
1867 -- Subscript reference. Check for Index_Checks suppressed
1869 if Is_Subscr_Ref then
1871 -- Check array type and its base type
1873 if Index_Checks_Suppressed (Arr_Typ)
1874 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1875 then
1876 return;
1878 -- Check array itself if it is an entity name
1880 elsif Is_Entity_Name (Arr)
1881 and then Index_Checks_Suppressed (Entity (Arr))
1882 then
1883 return;
1885 -- Check expression itself if it is an entity name
1887 elsif Is_Entity_Name (Expr)
1888 and then Index_Checks_Suppressed (Entity (Expr))
1889 then
1890 return;
1891 end if;
1893 -- All other cases, check for Range_Checks suppressed
1895 else
1896 -- Check target type and its base type
1898 if Range_Checks_Suppressed (Target_Typ)
1899 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1900 then
1901 return;
1903 -- Check expression itself if it is an entity name
1905 elsif Is_Entity_Name (Expr)
1906 and then Range_Checks_Suppressed (Entity (Expr))
1907 then
1908 return;
1910 -- If Expr is part of an assignment statement, then check left
1911 -- side of assignment if it is an entity name.
1913 elsif Nkind (Parnt) = N_Assignment_Statement
1914 and then Is_Entity_Name (Name (Parnt))
1915 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1916 then
1917 return;
1918 end if;
1919 end if;
1920 end if;
1922 -- Do not set range checks if they are killed
1924 if Nkind (Expr) = N_Unchecked_Type_Conversion
1925 and then Kill_Range_Check (Expr)
1926 then
1927 return;
1928 end if;
1930 -- Do not set range checks for any values from System.Scalar_Values
1931 -- since the whole idea of such values is to avoid checking them!
1933 if Is_Entity_Name (Expr)
1934 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1935 then
1936 return;
1937 end if;
1939 -- Now see if we need a check
1941 if No (Source_Typ) then
1942 S_Typ := Etype (Expr);
1943 else
1944 S_Typ := Source_Typ;
1945 end if;
1947 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1948 return;
1949 end if;
1951 Is_Unconstrained_Subscr_Ref :=
1952 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1954 -- Always do a range check if the source type includes infinities and
1955 -- the target type does not include infinities. We do not do this if
1956 -- range checks are killed.
1958 if Is_Floating_Point_Type (S_Typ)
1959 and then Has_Infinities (S_Typ)
1960 and then not Has_Infinities (Target_Typ)
1961 then
1962 Enable_Range_Check (Expr);
1963 end if;
1965 -- Return if we know expression is definitely in the range of the target
1966 -- type as determined by Determine_Range. Right now we only do this for
1967 -- discrete types, and not fixed-point or floating-point types.
1969 -- The additional less-precise tests below catch these cases
1971 -- Note: skip this if we are given a source_typ, since the point of
1972 -- supplying a Source_Typ is to stop us looking at the expression.
1973 -- We could sharpen this test to be out parameters only ???
1975 if Is_Discrete_Type (Target_Typ)
1976 and then Is_Discrete_Type (Etype (Expr))
1977 and then not Is_Unconstrained_Subscr_Ref
1978 and then No (Source_Typ)
1979 then
1980 declare
1981 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
1982 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1983 Lo : Uint;
1984 Hi : Uint;
1986 begin
1987 if Compile_Time_Known_Value (Tlo)
1988 and then Compile_Time_Known_Value (Thi)
1989 then
1990 declare
1991 Lov : constant Uint := Expr_Value (Tlo);
1992 Hiv : constant Uint := Expr_Value (Thi);
1994 begin
1995 -- If range is null, we for sure have a constraint error
1996 -- (we don't even need to look at the value involved,
1997 -- since all possible values will raise CE).
1999 if Lov > Hiv then
2000 Bad_Value;
2001 return;
2002 end if;
2004 -- Otherwise determine range of value
2006 Determine_Range (Expr, OK, Lo, Hi, Assume_Valid => True);
2008 if OK then
2010 -- If definitely in range, all OK
2012 if Lo >= Lov and then Hi <= Hiv then
2013 return;
2015 -- If definitely not in range, warn
2017 elsif Lov > Hi or else Hiv < Lo then
2018 Bad_Value;
2019 return;
2021 -- Otherwise we don't know
2023 else
2024 null;
2025 end if;
2026 end if;
2027 end;
2028 end if;
2029 end;
2030 end if;
2032 Int_Real :=
2033 Is_Floating_Point_Type (S_Typ)
2034 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
2036 -- Check if we can determine at compile time whether Expr is in the
2037 -- range of the target type. Note that if S_Typ is within the bounds
2038 -- of Target_Typ then this must be the case. This check is meaningful
2039 -- only if this is not a conversion between integer and real types.
2041 if not Is_Unconstrained_Subscr_Ref
2042 and then
2043 Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
2044 and then
2045 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
2046 or else
2047 Is_In_Range (Expr, Target_Typ,
2048 Assume_Valid => True,
2049 Fixed_Int => Fixed_Int,
2050 Int_Real => Int_Real))
2051 then
2052 return;
2054 elsif Is_Out_Of_Range (Expr, Target_Typ,
2055 Assume_Valid => True,
2056 Fixed_Int => Fixed_Int,
2057 Int_Real => Int_Real)
2058 then
2059 Bad_Value;
2060 return;
2062 -- In the floating-point case, we only do range checks if the type is
2063 -- constrained. We definitely do NOT want range checks for unconstrained
2064 -- types, since we want to have infinities
2066 elsif Is_Floating_Point_Type (S_Typ) then
2067 if Is_Constrained (S_Typ) then
2068 Enable_Range_Check (Expr);
2069 end if;
2071 -- For all other cases we enable a range check unconditionally
2073 else
2074 Enable_Range_Check (Expr);
2075 return;
2076 end if;
2077 end Apply_Scalar_Range_Check;
2079 ----------------------------------
2080 -- Apply_Selected_Length_Checks --
2081 ----------------------------------
2083 procedure Apply_Selected_Length_Checks
2084 (Ck_Node : Node_Id;
2085 Target_Typ : Entity_Id;
2086 Source_Typ : Entity_Id;
2087 Do_Static : Boolean)
2089 Cond : Node_Id;
2090 R_Result : Check_Result;
2091 R_Cno : Node_Id;
2093 Loc : constant Source_Ptr := Sloc (Ck_Node);
2094 Checks_On : constant Boolean :=
2095 (not Index_Checks_Suppressed (Target_Typ))
2096 or else
2097 (not Length_Checks_Suppressed (Target_Typ));
2099 begin
2100 if not Expander_Active then
2101 return;
2102 end if;
2104 R_Result :=
2105 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2107 for J in 1 .. 2 loop
2108 R_Cno := R_Result (J);
2109 exit when No (R_Cno);
2111 -- A length check may mention an Itype which is attached to a
2112 -- subsequent node. At the top level in a package this can cause
2113 -- an order-of-elaboration problem, so we make sure that the itype
2114 -- is referenced now.
2116 if Ekind (Current_Scope) = E_Package
2117 and then Is_Compilation_Unit (Current_Scope)
2118 then
2119 Ensure_Defined (Target_Typ, Ck_Node);
2121 if Present (Source_Typ) then
2122 Ensure_Defined (Source_Typ, Ck_Node);
2124 elsif Is_Itype (Etype (Ck_Node)) then
2125 Ensure_Defined (Etype (Ck_Node), Ck_Node);
2126 end if;
2127 end if;
2129 -- If the item is a conditional raise of constraint error, then have
2130 -- a look at what check is being performed and ???
2132 if Nkind (R_Cno) = N_Raise_Constraint_Error
2133 and then Present (Condition (R_Cno))
2134 then
2135 Cond := Condition (R_Cno);
2137 -- Case where node does not now have a dynamic check
2139 if not Has_Dynamic_Length_Check (Ck_Node) then
2141 -- If checks are on, just insert the check
2143 if Checks_On then
2144 Insert_Action (Ck_Node, R_Cno);
2146 if not Do_Static then
2147 Set_Has_Dynamic_Length_Check (Ck_Node);
2148 end if;
2150 -- If checks are off, then analyze the length check after
2151 -- temporarily attaching it to the tree in case the relevant
2152 -- condition can be evaluated at compile time. We still want a
2153 -- compile time warning in this case.
2155 else
2156 Set_Parent (R_Cno, Ck_Node);
2157 Analyze (R_Cno);
2158 end if;
2159 end if;
2161 -- Output a warning if the condition is known to be True
2163 if Is_Entity_Name (Cond)
2164 and then Entity (Cond) = Standard_True
2165 then
2166 Apply_Compile_Time_Constraint_Error
2167 (Ck_Node, "wrong length for array of}?",
2168 CE_Length_Check_Failed,
2169 Ent => Target_Typ,
2170 Typ => Target_Typ);
2172 -- If we were only doing a static check, or if checks are not
2173 -- on, then we want to delete the check, since it is not needed.
2174 -- We do this by replacing the if statement by a null statement
2176 elsif Do_Static or else not Checks_On then
2177 Remove_Warning_Messages (R_Cno);
2178 Rewrite (R_Cno, Make_Null_Statement (Loc));
2179 end if;
2181 else
2182 Install_Static_Check (R_Cno, Loc);
2183 end if;
2184 end loop;
2185 end Apply_Selected_Length_Checks;
2187 ---------------------------------
2188 -- Apply_Selected_Range_Checks --
2189 ---------------------------------
2191 procedure Apply_Selected_Range_Checks
2192 (Ck_Node : Node_Id;
2193 Target_Typ : Entity_Id;
2194 Source_Typ : Entity_Id;
2195 Do_Static : Boolean)
2197 Cond : Node_Id;
2198 R_Result : Check_Result;
2199 R_Cno : Node_Id;
2201 Loc : constant Source_Ptr := Sloc (Ck_Node);
2202 Checks_On : constant Boolean :=
2203 (not Index_Checks_Suppressed (Target_Typ))
2204 or else
2205 (not Range_Checks_Suppressed (Target_Typ));
2207 begin
2208 if not Expander_Active or else not Checks_On then
2209 return;
2210 end if;
2212 R_Result :=
2213 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2215 for J in 1 .. 2 loop
2217 R_Cno := R_Result (J);
2218 exit when No (R_Cno);
2220 -- If the item is a conditional raise of constraint error, then have
2221 -- a look at what check is being performed and ???
2223 if Nkind (R_Cno) = N_Raise_Constraint_Error
2224 and then Present (Condition (R_Cno))
2225 then
2226 Cond := Condition (R_Cno);
2228 if not Has_Dynamic_Range_Check (Ck_Node) then
2229 Insert_Action (Ck_Node, R_Cno);
2231 if not Do_Static then
2232 Set_Has_Dynamic_Range_Check (Ck_Node);
2233 end if;
2234 end if;
2236 -- Output a warning if the condition is known to be True
2238 if Is_Entity_Name (Cond)
2239 and then Entity (Cond) = Standard_True
2240 then
2241 -- Since an N_Range is technically not an expression, we have
2242 -- to set one of the bounds to C_E and then just flag the
2243 -- N_Range. The warning message will point to the lower bound
2244 -- and complain about a range, which seems OK.
2246 if Nkind (Ck_Node) = N_Range then
2247 Apply_Compile_Time_Constraint_Error
2248 (Low_Bound (Ck_Node), "static range out of bounds of}?",
2249 CE_Range_Check_Failed,
2250 Ent => Target_Typ,
2251 Typ => Target_Typ);
2253 Set_Raises_Constraint_Error (Ck_Node);
2255 else
2256 Apply_Compile_Time_Constraint_Error
2257 (Ck_Node, "static value out of range of}?",
2258 CE_Range_Check_Failed,
2259 Ent => Target_Typ,
2260 Typ => Target_Typ);
2261 end if;
2263 -- If we were only doing a static check, or if checks are not
2264 -- on, then we want to delete the check, since it is not needed.
2265 -- We do this by replacing the if statement by a null statement
2267 elsif Do_Static or else not Checks_On then
2268 Remove_Warning_Messages (R_Cno);
2269 Rewrite (R_Cno, Make_Null_Statement (Loc));
2270 end if;
2272 else
2273 Install_Static_Check (R_Cno, Loc);
2274 end if;
2275 end loop;
2276 end Apply_Selected_Range_Checks;
2278 -------------------------------
2279 -- Apply_Static_Length_Check --
2280 -------------------------------
2282 procedure Apply_Static_Length_Check
2283 (Expr : Node_Id;
2284 Target_Typ : Entity_Id;
2285 Source_Typ : Entity_Id := Empty)
2287 begin
2288 Apply_Selected_Length_Checks
2289 (Expr, Target_Typ, Source_Typ, Do_Static => True);
2290 end Apply_Static_Length_Check;
2292 -------------------------------------
2293 -- Apply_Subscript_Validity_Checks --
2294 -------------------------------------
2296 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2297 Sub : Node_Id;
2299 begin
2300 pragma Assert (Nkind (Expr) = N_Indexed_Component);
2302 -- Loop through subscripts
2304 Sub := First (Expressions (Expr));
2305 while Present (Sub) loop
2307 -- Check one subscript. Note that we do not worry about enumeration
2308 -- type with holes, since we will convert the value to a Pos value
2309 -- for the subscript, and that convert will do the necessary validity
2310 -- check.
2312 Ensure_Valid (Sub, Holes_OK => True);
2314 -- Move to next subscript
2316 Sub := Next (Sub);
2317 end loop;
2318 end Apply_Subscript_Validity_Checks;
2320 ----------------------------------
2321 -- Apply_Type_Conversion_Checks --
2322 ----------------------------------
2324 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2325 Target_Type : constant Entity_Id := Etype (N);
2326 Target_Base : constant Entity_Id := Base_Type (Target_Type);
2327 Expr : constant Node_Id := Expression (N);
2328 Expr_Type : constant Entity_Id := Etype (Expr);
2330 begin
2331 if Inside_A_Generic then
2332 return;
2334 -- Skip these checks if serious errors detected, there are some nasty
2335 -- situations of incomplete trees that blow things up.
2337 elsif Serious_Errors_Detected > 0 then
2338 return;
2340 -- Scalar type conversions of the form Target_Type (Expr) require a
2341 -- range check if we cannot be sure that Expr is in the base type of
2342 -- Target_Typ and also that Expr is in the range of Target_Typ. These
2343 -- are not quite the same condition from an implementation point of
2344 -- view, but clearly the second includes the first.
2346 elsif Is_Scalar_Type (Target_Type) then
2347 declare
2348 Conv_OK : constant Boolean := Conversion_OK (N);
2349 -- If the Conversion_OK flag on the type conversion is set and no
2350 -- floating point type is involved in the type conversion then
2351 -- fixed point values must be read as integral values.
2353 Float_To_Int : constant Boolean :=
2354 Is_Floating_Point_Type (Expr_Type)
2355 and then Is_Integer_Type (Target_Type);
2357 begin
2358 if not Overflow_Checks_Suppressed (Target_Base)
2359 and then not
2360 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
2361 and then not Float_To_Int
2362 then
2363 Activate_Overflow_Check (N);
2364 end if;
2366 if not Range_Checks_Suppressed (Target_Type)
2367 and then not Range_Checks_Suppressed (Expr_Type)
2368 then
2369 if Float_To_Int then
2370 Apply_Float_Conversion_Check (Expr, Target_Type);
2371 else
2372 Apply_Scalar_Range_Check
2373 (Expr, Target_Type, Fixed_Int => Conv_OK);
2374 end if;
2375 end if;
2376 end;
2378 elsif Comes_From_Source (N)
2379 and then not Discriminant_Checks_Suppressed (Target_Type)
2380 and then Is_Record_Type (Target_Type)
2381 and then Is_Derived_Type (Target_Type)
2382 and then not Is_Tagged_Type (Target_Type)
2383 and then not Is_Constrained (Target_Type)
2384 and then Present (Stored_Constraint (Target_Type))
2385 then
2386 -- An unconstrained derived type may have inherited discriminant
2387 -- Build an actual discriminant constraint list using the stored
2388 -- constraint, to verify that the expression of the parent type
2389 -- satisfies the constraints imposed by the (unconstrained!)
2390 -- derived type. This applies to value conversions, not to view
2391 -- conversions of tagged types.
2393 declare
2394 Loc : constant Source_Ptr := Sloc (N);
2395 Cond : Node_Id;
2396 Constraint : Elmt_Id;
2397 Discr_Value : Node_Id;
2398 Discr : Entity_Id;
2400 New_Constraints : constant Elist_Id := New_Elmt_List;
2401 Old_Constraints : constant Elist_Id :=
2402 Discriminant_Constraint (Expr_Type);
2404 begin
2405 Constraint := First_Elmt (Stored_Constraint (Target_Type));
2406 while Present (Constraint) loop
2407 Discr_Value := Node (Constraint);
2409 if Is_Entity_Name (Discr_Value)
2410 and then Ekind (Entity (Discr_Value)) = E_Discriminant
2411 then
2412 Discr := Corresponding_Discriminant (Entity (Discr_Value));
2414 if Present (Discr)
2415 and then Scope (Discr) = Base_Type (Expr_Type)
2416 then
2417 -- Parent is constrained by new discriminant. Obtain
2418 -- Value of original discriminant in expression. If the
2419 -- new discriminant has been used to constrain more than
2420 -- one of the stored discriminants, this will provide the
2421 -- required consistency check.
2423 Append_Elmt
2424 (Make_Selected_Component (Loc,
2425 Prefix =>
2426 Duplicate_Subexpr_No_Checks
2427 (Expr, Name_Req => True),
2428 Selector_Name =>
2429 Make_Identifier (Loc, Chars (Discr))),
2430 New_Constraints);
2432 else
2433 -- Discriminant of more remote ancestor ???
2435 return;
2436 end if;
2438 -- Derived type definition has an explicit value for this
2439 -- stored discriminant.
2441 else
2442 Append_Elmt
2443 (Duplicate_Subexpr_No_Checks (Discr_Value),
2444 New_Constraints);
2445 end if;
2447 Next_Elmt (Constraint);
2448 end loop;
2450 -- Use the unconstrained expression type to retrieve the
2451 -- discriminants of the parent, and apply momentarily the
2452 -- discriminant constraint synthesized above.
2454 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2455 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2456 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2458 Insert_Action (N,
2459 Make_Raise_Constraint_Error (Loc,
2460 Condition => Cond,
2461 Reason => CE_Discriminant_Check_Failed));
2462 end;
2464 -- For arrays, conversions are applied during expansion, to take into
2465 -- accounts changes of representation. The checks become range checks on
2466 -- the base type or length checks on the subtype, depending on whether
2467 -- the target type is unconstrained or constrained.
2469 else
2470 null;
2471 end if;
2472 end Apply_Type_Conversion_Checks;
2474 ----------------------------------------------
2475 -- Apply_Universal_Integer_Attribute_Checks --
2476 ----------------------------------------------
2478 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2479 Loc : constant Source_Ptr := Sloc (N);
2480 Typ : constant Entity_Id := Etype (N);
2482 begin
2483 if Inside_A_Generic then
2484 return;
2486 -- Nothing to do if checks are suppressed
2488 elsif Range_Checks_Suppressed (Typ)
2489 and then Overflow_Checks_Suppressed (Typ)
2490 then
2491 return;
2493 -- Nothing to do if the attribute does not come from source. The
2494 -- internal attributes we generate of this type do not need checks,
2495 -- and furthermore the attempt to check them causes some circular
2496 -- elaboration orders when dealing with packed types.
2498 elsif not Comes_From_Source (N) then
2499 return;
2501 -- If the prefix is a selected component that depends on a discriminant
2502 -- the check may improperly expose a discriminant instead of using
2503 -- the bounds of the object itself. Set the type of the attribute to
2504 -- the base type of the context, so that a check will be imposed when
2505 -- needed (e.g. if the node appears as an index).
2507 elsif Nkind (Prefix (N)) = N_Selected_Component
2508 and then Ekind (Typ) = E_Signed_Integer_Subtype
2509 and then Depends_On_Discriminant (Scalar_Range (Typ))
2510 then
2511 Set_Etype (N, Base_Type (Typ));
2513 -- Otherwise, replace the attribute node with a type conversion node
2514 -- whose expression is the attribute, retyped to universal integer, and
2515 -- whose subtype mark is the target type. The call to analyze this
2516 -- conversion will set range and overflow checks as required for proper
2517 -- detection of an out of range value.
2519 else
2520 Set_Etype (N, Universal_Integer);
2521 Set_Analyzed (N, True);
2523 Rewrite (N,
2524 Make_Type_Conversion (Loc,
2525 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2526 Expression => Relocate_Node (N)));
2528 Analyze_And_Resolve (N, Typ);
2529 return;
2530 end if;
2531 end Apply_Universal_Integer_Attribute_Checks;
2533 -------------------------------
2534 -- Build_Discriminant_Checks --
2535 -------------------------------
2537 function Build_Discriminant_Checks
2538 (N : Node_Id;
2539 T_Typ : Entity_Id) return Node_Id
2541 Loc : constant Source_Ptr := Sloc (N);
2542 Cond : Node_Id;
2543 Disc : Elmt_Id;
2544 Disc_Ent : Entity_Id;
2545 Dref : Node_Id;
2546 Dval : Node_Id;
2548 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2550 ----------------------------------
2551 -- Aggregate_Discriminant_Value --
2552 ----------------------------------
2554 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2555 Assoc : Node_Id;
2557 begin
2558 -- The aggregate has been normalized with named associations. We use
2559 -- the Chars field to locate the discriminant to take into account
2560 -- discriminants in derived types, which carry the same name as those
2561 -- in the parent.
2563 Assoc := First (Component_Associations (N));
2564 while Present (Assoc) loop
2565 if Chars (First (Choices (Assoc))) = Chars (Disc) then
2566 return Expression (Assoc);
2567 else
2568 Next (Assoc);
2569 end if;
2570 end loop;
2572 -- Discriminant must have been found in the loop above
2574 raise Program_Error;
2575 end Aggregate_Discriminant_Val;
2577 -- Start of processing for Build_Discriminant_Checks
2579 begin
2580 -- Loop through discriminants evolving the condition
2582 Cond := Empty;
2583 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2585 -- For a fully private type, use the discriminants of the parent type
2587 if Is_Private_Type (T_Typ)
2588 and then No (Full_View (T_Typ))
2589 then
2590 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2591 else
2592 Disc_Ent := First_Discriminant (T_Typ);
2593 end if;
2595 while Present (Disc) loop
2596 Dval := Node (Disc);
2598 if Nkind (Dval) = N_Identifier
2599 and then Ekind (Entity (Dval)) = E_Discriminant
2600 then
2601 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2602 else
2603 Dval := Duplicate_Subexpr_No_Checks (Dval);
2604 end if;
2606 -- If we have an Unchecked_Union node, we can infer the discriminants
2607 -- of the node.
2609 if Is_Unchecked_Union (Base_Type (T_Typ)) then
2610 Dref := New_Copy (
2611 Get_Discriminant_Value (
2612 First_Discriminant (T_Typ),
2613 T_Typ,
2614 Stored_Constraint (T_Typ)));
2616 elsif Nkind (N) = N_Aggregate then
2617 Dref :=
2618 Duplicate_Subexpr_No_Checks
2619 (Aggregate_Discriminant_Val (Disc_Ent));
2621 else
2622 Dref :=
2623 Make_Selected_Component (Loc,
2624 Prefix =>
2625 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2626 Selector_Name =>
2627 Make_Identifier (Loc, Chars (Disc_Ent)));
2629 Set_Is_In_Discriminant_Check (Dref);
2630 end if;
2632 Evolve_Or_Else (Cond,
2633 Make_Op_Ne (Loc,
2634 Left_Opnd => Dref,
2635 Right_Opnd => Dval));
2637 Next_Elmt (Disc);
2638 Next_Discriminant (Disc_Ent);
2639 end loop;
2641 return Cond;
2642 end Build_Discriminant_Checks;
2644 ------------------
2645 -- Check_Needed --
2646 ------------------
2648 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2649 N : Node_Id;
2650 P : Node_Id;
2651 K : Node_Kind;
2652 L : Node_Id;
2653 R : Node_Id;
2655 begin
2656 -- Always check if not simple entity
2658 if Nkind (Nod) not in N_Has_Entity
2659 or else not Comes_From_Source (Nod)
2660 then
2661 return True;
2662 end if;
2664 -- Look up tree for short circuit
2666 N := Nod;
2667 loop
2668 P := Parent (N);
2669 K := Nkind (P);
2671 -- Done if out of subexpression (note that we allow generated stuff
2672 -- such as itype declarations in this context, to keep the loop going
2673 -- since we may well have generated such stuff in complex situations.
2674 -- Also done if no parent (probably an error condition, but no point
2675 -- in behaving nasty if we find it!)
2677 if No (P)
2678 or else (K not in N_Subexpr and then Comes_From_Source (P))
2679 then
2680 return True;
2682 -- Or/Or Else case, where test is part of the right operand, or is
2683 -- part of one of the actions associated with the right operand, and
2684 -- the left operand is an equality test.
2686 elsif K = N_Op_Or then
2687 exit when N = Right_Opnd (P)
2688 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2690 elsif K = N_Or_Else then
2691 exit when (N = Right_Opnd (P)
2692 or else
2693 (Is_List_Member (N)
2694 and then List_Containing (N) = Actions (P)))
2695 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2697 -- Similar test for the And/And then case, where the left operand
2698 -- is an inequality test.
2700 elsif K = N_Op_And then
2701 exit when N = Right_Opnd (P)
2702 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2704 elsif K = N_And_Then then
2705 exit when (N = Right_Opnd (P)
2706 or else
2707 (Is_List_Member (N)
2708 and then List_Containing (N) = Actions (P)))
2709 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2710 end if;
2712 N := P;
2713 end loop;
2715 -- If we fall through the loop, then we have a conditional with an
2716 -- appropriate test as its left operand. So test further.
2718 L := Left_Opnd (P);
2719 R := Right_Opnd (L);
2720 L := Left_Opnd (L);
2722 -- Left operand of test must match original variable
2724 if Nkind (L) not in N_Has_Entity
2725 or else Entity (L) /= Entity (Nod)
2726 then
2727 return True;
2728 end if;
2730 -- Right operand of test must be key value (zero or null)
2732 case Check is
2733 when Access_Check =>
2734 if not Known_Null (R) then
2735 return True;
2736 end if;
2738 when Division_Check =>
2739 if not Compile_Time_Known_Value (R)
2740 or else Expr_Value (R) /= Uint_0
2741 then
2742 return True;
2743 end if;
2745 when others =>
2746 raise Program_Error;
2747 end case;
2749 -- Here we have the optimizable case, warn if not short-circuited
2751 if K = N_Op_And or else K = N_Op_Or then
2752 case Check is
2753 when Access_Check =>
2754 Error_Msg_N
2755 ("Constraint_Error may be raised (access check)?",
2756 Parent (Nod));
2757 when Division_Check =>
2758 Error_Msg_N
2759 ("Constraint_Error may be raised (zero divide)?",
2760 Parent (Nod));
2762 when others =>
2763 raise Program_Error;
2764 end case;
2766 if K = N_Op_And then
2767 Error_Msg_N -- CODEFIX
2768 ("use `AND THEN` instead of AND?", P);
2769 else
2770 Error_Msg_N -- CODEFIX
2771 ("use `OR ELSE` instead of OR?", P);
2772 end if;
2774 -- If not short-circuited, we need the check
2776 return True;
2778 -- If short-circuited, we can omit the check
2780 else
2781 return False;
2782 end if;
2783 end Check_Needed;
2785 -----------------------------------
2786 -- Check_Valid_Lvalue_Subscripts --
2787 -----------------------------------
2789 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2790 begin
2791 -- Skip this if range checks are suppressed
2793 if Range_Checks_Suppressed (Etype (Expr)) then
2794 return;
2796 -- Only do this check for expressions that come from source. We assume
2797 -- that expander generated assignments explicitly include any necessary
2798 -- checks. Note that this is not just an optimization, it avoids
2799 -- infinite recursions!
2801 elsif not Comes_From_Source (Expr) then
2802 return;
2804 -- For a selected component, check the prefix
2806 elsif Nkind (Expr) = N_Selected_Component then
2807 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2808 return;
2810 -- Case of indexed component
2812 elsif Nkind (Expr) = N_Indexed_Component then
2813 Apply_Subscript_Validity_Checks (Expr);
2815 -- Prefix may itself be or contain an indexed component, and these
2816 -- subscripts need checking as well.
2818 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2819 end if;
2820 end Check_Valid_Lvalue_Subscripts;
2822 ----------------------------------
2823 -- Null_Exclusion_Static_Checks --
2824 ----------------------------------
2826 procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2827 Error_Node : Node_Id;
2828 Expr : Node_Id;
2829 Has_Null : constant Boolean := Has_Null_Exclusion (N);
2830 K : constant Node_Kind := Nkind (N);
2831 Typ : Entity_Id;
2833 begin
2834 pragma Assert
2835 (K = N_Component_Declaration
2836 or else K = N_Discriminant_Specification
2837 or else K = N_Function_Specification
2838 or else K = N_Object_Declaration
2839 or else K = N_Parameter_Specification);
2841 if K = N_Function_Specification then
2842 Typ := Etype (Defining_Entity (N));
2843 else
2844 Typ := Etype (Defining_Identifier (N));
2845 end if;
2847 case K is
2848 when N_Component_Declaration =>
2849 if Present (Access_Definition (Component_Definition (N))) then
2850 Error_Node := Component_Definition (N);
2851 else
2852 Error_Node := Subtype_Indication (Component_Definition (N));
2853 end if;
2855 when N_Discriminant_Specification =>
2856 Error_Node := Discriminant_Type (N);
2858 when N_Function_Specification =>
2859 Error_Node := Result_Definition (N);
2861 when N_Object_Declaration =>
2862 Error_Node := Object_Definition (N);
2864 when N_Parameter_Specification =>
2865 Error_Node := Parameter_Type (N);
2867 when others =>
2868 raise Program_Error;
2869 end case;
2871 if Has_Null then
2873 -- Enforce legality rule 3.10 (13): A null exclusion can only be
2874 -- applied to an access [sub]type.
2876 if not Is_Access_Type (Typ) then
2877 Error_Msg_N
2878 ("`NOT NULL` allowed only for an access type", Error_Node);
2880 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
2881 -- be applied to a [sub]type that does not exclude null already.
2883 elsif Can_Never_Be_Null (Typ)
2884 and then Comes_From_Source (Typ)
2885 then
2886 Error_Msg_NE
2887 ("`NOT NULL` not allowed (& already excludes null)",
2888 Error_Node, Typ);
2889 end if;
2890 end if;
2892 -- Check that null-excluding objects are always initialized, except for
2893 -- deferred constants, for which the expression will appear in the full
2894 -- declaration.
2896 if K = N_Object_Declaration
2897 and then No (Expression (N))
2898 and then not Constant_Present (N)
2899 and then not No_Initialization (N)
2900 then
2901 -- Add an expression that assigns null. This node is needed by
2902 -- Apply_Compile_Time_Constraint_Error, which will replace this with
2903 -- a Constraint_Error node.
2905 Set_Expression (N, Make_Null (Sloc (N)));
2906 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2908 Apply_Compile_Time_Constraint_Error
2909 (N => Expression (N),
2910 Msg => "(Ada 2005) null-excluding objects must be initialized?",
2911 Reason => CE_Null_Not_Allowed);
2912 end if;
2914 -- Check that a null-excluding component, formal or object is not being
2915 -- assigned a null value. Otherwise generate a warning message and
2916 -- replace Expression (N) by an N_Constraint_Error node.
2918 if K /= N_Function_Specification then
2919 Expr := Expression (N);
2921 if Present (Expr) and then Known_Null (Expr) then
2922 case K is
2923 when N_Component_Declaration |
2924 N_Discriminant_Specification =>
2925 Apply_Compile_Time_Constraint_Error
2926 (N => Expr,
2927 Msg => "(Ada 2005) null not allowed " &
2928 "in null-excluding components?",
2929 Reason => CE_Null_Not_Allowed);
2931 when N_Object_Declaration =>
2932 Apply_Compile_Time_Constraint_Error
2933 (N => Expr,
2934 Msg => "(Ada 2005) null not allowed " &
2935 "in null-excluding objects?",
2936 Reason => CE_Null_Not_Allowed);
2938 when N_Parameter_Specification =>
2939 Apply_Compile_Time_Constraint_Error
2940 (N => Expr,
2941 Msg => "(Ada 2005) null not allowed " &
2942 "in null-excluding formals?",
2943 Reason => CE_Null_Not_Allowed);
2945 when others =>
2946 null;
2947 end case;
2948 end if;
2949 end if;
2950 end Null_Exclusion_Static_Checks;
2952 ----------------------------------
2953 -- Conditional_Statements_Begin --
2954 ----------------------------------
2956 procedure Conditional_Statements_Begin is
2957 begin
2958 Saved_Checks_TOS := Saved_Checks_TOS + 1;
2960 -- If stack overflows, kill all checks, that way we know to simply reset
2961 -- the number of saved checks to zero on return. This should never occur
2962 -- in practice.
2964 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2965 Kill_All_Checks;
2967 -- In the normal case, we just make a new stack entry saving the current
2968 -- number of saved checks for a later restore.
2970 else
2971 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2973 if Debug_Flag_CC then
2974 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2975 Num_Saved_Checks);
2976 end if;
2977 end if;
2978 end Conditional_Statements_Begin;
2980 --------------------------------
2981 -- Conditional_Statements_End --
2982 --------------------------------
2984 procedure Conditional_Statements_End is
2985 begin
2986 pragma Assert (Saved_Checks_TOS > 0);
2988 -- If the saved checks stack overflowed, then we killed all checks, so
2989 -- setting the number of saved checks back to zero is correct. This
2990 -- should never occur in practice.
2992 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2993 Num_Saved_Checks := 0;
2995 -- In the normal case, restore the number of saved checks from the top
2996 -- stack entry.
2998 else
2999 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
3000 if Debug_Flag_CC then
3001 w ("Conditional_Statements_End: Num_Saved_Checks = ",
3002 Num_Saved_Checks);
3003 end if;
3004 end if;
3006 Saved_Checks_TOS := Saved_Checks_TOS - 1;
3007 end Conditional_Statements_End;
3009 ---------------------
3010 -- Determine_Range --
3011 ---------------------
3013 Cache_Size : constant := 2 ** 10;
3014 type Cache_Index is range 0 .. Cache_Size - 1;
3015 -- Determine size of below cache (power of 2 is more efficient!)
3017 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
3018 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
3019 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
3020 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
3021 -- The above arrays are used to implement a small direct cache for
3022 -- Determine_Range calls. Because of the way Determine_Range recursively
3023 -- traces subexpressions, and because overflow checking calls the routine
3024 -- on the way up the tree, a quadratic behavior can otherwise be
3025 -- encountered in large expressions. The cache entry for node N is stored
3026 -- in the (N mod Cache_Size) entry, and can be validated by checking the
3027 -- actual node value stored there. The Range_Cache_V array records the
3028 -- setting of Assume_Valid for the cache entry.
3030 procedure Determine_Range
3031 (N : Node_Id;
3032 OK : out Boolean;
3033 Lo : out Uint;
3034 Hi : out Uint;
3035 Assume_Valid : Boolean := False)
3037 Typ : Entity_Id := Etype (N);
3038 -- Type to use, may get reset to base type for possibly invalid entity
3040 Lo_Left : Uint;
3041 Hi_Left : Uint;
3042 -- Lo and Hi bounds of left operand
3044 Lo_Right : Uint;
3045 Hi_Right : Uint;
3046 -- Lo and Hi bounds of right (or only) operand
3048 Bound : Node_Id;
3049 -- Temp variable used to hold a bound node
3051 Hbound : Uint;
3052 -- High bound of base type of expression
3054 Lor : Uint;
3055 Hir : Uint;
3056 -- Refined values for low and high bounds, after tightening
3058 OK1 : Boolean;
3059 -- Used in lower level calls to indicate if call succeeded
3061 Cindex : Cache_Index;
3062 -- Used to search cache
3064 function OK_Operands return Boolean;
3065 -- Used for binary operators. Determines the ranges of the left and
3066 -- right operands, and if they are both OK, returns True, and puts
3067 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
3069 -----------------
3070 -- OK_Operands --
3071 -----------------
3073 function OK_Operands return Boolean is
3074 begin
3075 Determine_Range
3076 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
3078 if not OK1 then
3079 return False;
3080 end if;
3082 Determine_Range
3083 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3084 return OK1;
3085 end OK_Operands;
3087 -- Start of processing for Determine_Range
3089 begin
3090 -- Prevent junk warnings by initializing range variables
3092 Lo := No_Uint;
3093 Hi := No_Uint;
3094 Lor := No_Uint;
3095 Hir := No_Uint;
3097 -- If type is not defined, we can't determine its range
3099 if No (Typ)
3101 -- We don't deal with anything except discrete types
3103 or else not Is_Discrete_Type (Typ)
3105 -- Ignore type for which an error has been posted, since range in
3106 -- this case may well be a bogosity deriving from the error. Also
3107 -- ignore if error posted on the reference node.
3109 or else Error_Posted (N) or else Error_Posted (Typ)
3110 then
3111 OK := False;
3112 return;
3113 end if;
3115 -- For all other cases, we can determine the range
3117 OK := True;
3119 -- If value is compile time known, then the possible range is the one
3120 -- value that we know this expression definitely has!
3122 if Compile_Time_Known_Value (N) then
3123 Lo := Expr_Value (N);
3124 Hi := Lo;
3125 return;
3126 end if;
3128 -- Return if already in the cache
3130 Cindex := Cache_Index (N mod Cache_Size);
3132 if Determine_Range_Cache_N (Cindex) = N
3133 and then
3134 Determine_Range_Cache_V (Cindex) = Assume_Valid
3135 then
3136 Lo := Determine_Range_Cache_Lo (Cindex);
3137 Hi := Determine_Range_Cache_Hi (Cindex);
3138 return;
3139 end if;
3141 -- Otherwise, start by finding the bounds of the type of the expression,
3142 -- the value cannot be outside this range (if it is, then we have an
3143 -- overflow situation, which is a separate check, we are talking here
3144 -- only about the expression value).
3146 -- First a check, never try to find the bounds of a generic type, since
3147 -- these bounds are always junk values, and it is only valid to look at
3148 -- the bounds in an instance.
3150 if Is_Generic_Type (Typ) then
3151 OK := False;
3152 return;
3153 end if;
3155 -- First step, change to use base type unless we know the value is valid
3157 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
3158 or else Assume_No_Invalid_Values
3159 or else Assume_Valid
3160 then
3161 null;
3162 else
3163 Typ := Underlying_Type (Base_Type (Typ));
3164 end if;
3166 -- We use the actual bound unless it is dynamic, in which case use the
3167 -- corresponding base type bound if possible. If we can't get a bound
3168 -- then we figure we can't determine the range (a peculiar case, that
3169 -- perhaps cannot happen, but there is no point in bombing in this
3170 -- optimization circuit.
3172 -- First the low bound
3174 Bound := Type_Low_Bound (Typ);
3176 if Compile_Time_Known_Value (Bound) then
3177 Lo := Expr_Value (Bound);
3179 elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
3180 Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
3182 else
3183 OK := False;
3184 return;
3185 end if;
3187 -- Now the high bound
3189 Bound := Type_High_Bound (Typ);
3191 -- We need the high bound of the base type later on, and this should
3192 -- always be compile time known. Again, it is not clear that this
3193 -- can ever be false, but no point in bombing.
3195 if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
3196 Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
3197 Hi := Hbound;
3199 else
3200 OK := False;
3201 return;
3202 end if;
3204 -- If we have a static subtype, then that may have a tighter bound so
3205 -- use the upper bound of the subtype instead in this case.
3207 if Compile_Time_Known_Value (Bound) then
3208 Hi := Expr_Value (Bound);
3209 end if;
3211 -- We may be able to refine this value in certain situations. If any
3212 -- refinement is possible, then Lor and Hir are set to possibly tighter
3213 -- bounds, and OK1 is set to True.
3215 case Nkind (N) is
3217 -- For unary plus, result is limited by range of operand
3219 when N_Op_Plus =>
3220 Determine_Range
3221 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
3223 -- For unary minus, determine range of operand, and negate it
3225 when N_Op_Minus =>
3226 Determine_Range
3227 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3229 if OK1 then
3230 Lor := -Hi_Right;
3231 Hir := -Lo_Right;
3232 end if;
3234 -- For binary addition, get range of each operand and do the
3235 -- addition to get the result range.
3237 when N_Op_Add =>
3238 if OK_Operands then
3239 Lor := Lo_Left + Lo_Right;
3240 Hir := Hi_Left + Hi_Right;
3241 end if;
3243 -- Division is tricky. The only case we consider is where the right
3244 -- operand is a positive constant, and in this case we simply divide
3245 -- the bounds of the left operand
3247 when N_Op_Divide =>
3248 if OK_Operands then
3249 if Lo_Right = Hi_Right
3250 and then Lo_Right > 0
3251 then
3252 Lor := Lo_Left / Lo_Right;
3253 Hir := Hi_Left / Lo_Right;
3255 else
3256 OK1 := False;
3257 end if;
3258 end if;
3260 -- For binary subtraction, get range of each operand and do the worst
3261 -- case subtraction to get the result range.
3263 when N_Op_Subtract =>
3264 if OK_Operands then
3265 Lor := Lo_Left - Hi_Right;
3266 Hir := Hi_Left - Lo_Right;
3267 end if;
3269 -- For MOD, if right operand is a positive constant, then result must
3270 -- be in the allowable range of mod results.
3272 when N_Op_Mod =>
3273 if OK_Operands then
3274 if Lo_Right = Hi_Right
3275 and then Lo_Right /= 0
3276 then
3277 if Lo_Right > 0 then
3278 Lor := Uint_0;
3279 Hir := Lo_Right - 1;
3281 else -- Lo_Right < 0
3282 Lor := Lo_Right + 1;
3283 Hir := Uint_0;
3284 end if;
3286 else
3287 OK1 := False;
3288 end if;
3289 end if;
3291 -- For REM, if right operand is a positive constant, then result must
3292 -- be in the allowable range of mod results.
3294 when N_Op_Rem =>
3295 if OK_Operands then
3296 if Lo_Right = Hi_Right
3297 and then Lo_Right /= 0
3298 then
3299 declare
3300 Dval : constant Uint := (abs Lo_Right) - 1;
3302 begin
3303 -- The sign of the result depends on the sign of the
3304 -- dividend (but not on the sign of the divisor, hence
3305 -- the abs operation above).
3307 if Lo_Left < 0 then
3308 Lor := -Dval;
3309 else
3310 Lor := Uint_0;
3311 end if;
3313 if Hi_Left < 0 then
3314 Hir := Uint_0;
3315 else
3316 Hir := Dval;
3317 end if;
3318 end;
3320 else
3321 OK1 := False;
3322 end if;
3323 end if;
3325 -- Attribute reference cases
3327 when N_Attribute_Reference =>
3328 case Attribute_Name (N) is
3330 -- For Pos/Val attributes, we can refine the range using the
3331 -- possible range of values of the attribute expression.
3333 when Name_Pos | Name_Val =>
3334 Determine_Range
3335 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
3337 -- For Length attribute, use the bounds of the corresponding
3338 -- index type to refine the range.
3340 when Name_Length =>
3341 declare
3342 Atyp : Entity_Id := Etype (Prefix (N));
3343 Inum : Nat;
3344 Indx : Node_Id;
3346 LL, LU : Uint;
3347 UL, UU : Uint;
3349 begin
3350 if Is_Access_Type (Atyp) then
3351 Atyp := Designated_Type (Atyp);
3352 end if;
3354 -- For string literal, we know exact value
3356 if Ekind (Atyp) = E_String_Literal_Subtype then
3357 OK := True;
3358 Lo := String_Literal_Length (Atyp);
3359 Hi := String_Literal_Length (Atyp);
3360 return;
3361 end if;
3363 -- Otherwise check for expression given
3365 if No (Expressions (N)) then
3366 Inum := 1;
3367 else
3368 Inum :=
3369 UI_To_Int (Expr_Value (First (Expressions (N))));
3370 end if;
3372 Indx := First_Index (Atyp);
3373 for J in 2 .. Inum loop
3374 Indx := Next_Index (Indx);
3375 end loop;
3377 -- If the index type is a formal type or derived from
3378 -- one, the bounds are not static.
3380 if Is_Generic_Type (Root_Type (Etype (Indx))) then
3381 OK := False;
3382 return;
3383 end if;
3385 Determine_Range
3386 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
3387 Assume_Valid);
3389 if OK1 then
3390 Determine_Range
3391 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
3392 Assume_Valid);
3394 if OK1 then
3396 -- The maximum value for Length is the biggest
3397 -- possible gap between the values of the bounds.
3398 -- But of course, this value cannot be negative.
3400 Hir := UI_Max (Uint_0, UU - LL + 1);
3402 -- For constrained arrays, the minimum value for
3403 -- Length is taken from the actual value of the
3404 -- bounds, since the index will be exactly of this
3405 -- subtype.
3407 if Is_Constrained (Atyp) then
3408 Lor := UI_Max (Uint_0, UL - LU + 1);
3410 -- For an unconstrained array, the minimum value
3411 -- for length is always zero.
3413 else
3414 Lor := Uint_0;
3415 end if;
3416 end if;
3417 end if;
3418 end;
3420 -- No special handling for other attributes
3421 -- Probably more opportunities exist here???
3423 when others =>
3424 OK1 := False;
3426 end case;
3428 -- For type conversion from one discrete type to another, we can
3429 -- refine the range using the converted value.
3431 when N_Type_Conversion =>
3432 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
3434 -- Nothing special to do for all other expression kinds
3436 when others =>
3437 OK1 := False;
3438 Lor := No_Uint;
3439 Hir := No_Uint;
3440 end case;
3442 -- At this stage, if OK1 is true, then we know that the actual result of
3443 -- the computed expression is in the range Lor .. Hir. We can use this
3444 -- to restrict the possible range of results.
3446 if OK1 then
3448 -- If the refined value of the low bound is greater than the type
3449 -- high bound, then reset it to the more restrictive value. However,
3450 -- we do NOT do this for the case of a modular type where the
3451 -- possible upper bound on the value is above the base type high
3452 -- bound, because that means the result could wrap.
3454 if Lor > Lo
3455 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
3456 then
3457 Lo := Lor;
3458 end if;
3460 -- Similarly, if the refined value of the high bound is less than the
3461 -- value so far, then reset it to the more restrictive value. Again,
3462 -- we do not do this if the refined low bound is negative for a
3463 -- modular type, since this would wrap.
3465 if Hir < Hi
3466 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
3467 then
3468 Hi := Hir;
3469 end if;
3470 end if;
3472 -- Set cache entry for future call and we are all done
3474 Determine_Range_Cache_N (Cindex) := N;
3475 Determine_Range_Cache_V (Cindex) := Assume_Valid;
3476 Determine_Range_Cache_Lo (Cindex) := Lo;
3477 Determine_Range_Cache_Hi (Cindex) := Hi;
3478 return;
3480 -- If any exception occurs, it means that we have some bug in the compiler,
3481 -- possibly triggered by a previous error, or by some unforeseen peculiar
3482 -- occurrence. However, this is only an optimization attempt, so there is
3483 -- really no point in crashing the compiler. Instead we just decide, too
3484 -- bad, we can't figure out a range in this case after all.
3486 exception
3487 when others =>
3489 -- Debug flag K disables this behavior (useful for debugging)
3491 if Debug_Flag_K then
3492 raise;
3493 else
3494 OK := False;
3495 Lo := No_Uint;
3496 Hi := No_Uint;
3497 return;
3498 end if;
3499 end Determine_Range;
3501 ------------------------------------
3502 -- Discriminant_Checks_Suppressed --
3503 ------------------------------------
3505 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3506 begin
3507 if Present (E) then
3508 if Is_Unchecked_Union (E) then
3509 return True;
3510 elsif Checks_May_Be_Suppressed (E) then
3511 return Is_Check_Suppressed (E, Discriminant_Check);
3512 end if;
3513 end if;
3515 return Scope_Suppress (Discriminant_Check);
3516 end Discriminant_Checks_Suppressed;
3518 --------------------------------
3519 -- Division_Checks_Suppressed --
3520 --------------------------------
3522 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3523 begin
3524 if Present (E) and then Checks_May_Be_Suppressed (E) then
3525 return Is_Check_Suppressed (E, Division_Check);
3526 else
3527 return Scope_Suppress (Division_Check);
3528 end if;
3529 end Division_Checks_Suppressed;
3531 -----------------------------------
3532 -- Elaboration_Checks_Suppressed --
3533 -----------------------------------
3535 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3536 begin
3537 -- The complication in this routine is that if we are in the dynamic
3538 -- model of elaboration, we also check All_Checks, since All_Checks
3539 -- does not set Elaboration_Check explicitly.
3541 if Present (E) then
3542 if Kill_Elaboration_Checks (E) then
3543 return True;
3545 elsif Checks_May_Be_Suppressed (E) then
3546 if Is_Check_Suppressed (E, Elaboration_Check) then
3547 return True;
3548 elsif Dynamic_Elaboration_Checks then
3549 return Is_Check_Suppressed (E, All_Checks);
3550 else
3551 return False;
3552 end if;
3553 end if;
3554 end if;
3556 if Scope_Suppress (Elaboration_Check) then
3557 return True;
3558 elsif Dynamic_Elaboration_Checks then
3559 return Scope_Suppress (All_Checks);
3560 else
3561 return False;
3562 end if;
3563 end Elaboration_Checks_Suppressed;
3565 ---------------------------
3566 -- Enable_Overflow_Check --
3567 ---------------------------
3569 procedure Enable_Overflow_Check (N : Node_Id) is
3570 Typ : constant Entity_Id := Base_Type (Etype (N));
3571 Chk : Nat;
3572 OK : Boolean;
3573 Ent : Entity_Id;
3574 Ofs : Uint;
3575 Lo : Uint;
3576 Hi : Uint;
3578 begin
3579 if Debug_Flag_CC then
3580 w ("Enable_Overflow_Check for node ", Int (N));
3581 Write_Str (" Source location = ");
3582 wl (Sloc (N));
3583 pg (Union_Id (N));
3584 end if;
3586 -- No check if overflow checks suppressed for type of node
3588 if Present (Etype (N))
3589 and then Overflow_Checks_Suppressed (Etype (N))
3590 then
3591 return;
3593 -- Nothing to do for unsigned integer types, which do not overflow
3595 elsif Is_Modular_Integer_Type (Typ) then
3596 return;
3598 -- Nothing to do if the range of the result is known OK. We skip this
3599 -- for conversions, since the caller already did the check, and in any
3600 -- case the condition for deleting the check for a type conversion is
3601 -- different.
3603 elsif Nkind (N) /= N_Type_Conversion then
3604 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
3606 -- Note in the test below that we assume that the range is not OK
3607 -- if a bound of the range is equal to that of the type. That's not
3608 -- quite accurate but we do this for the following reasons:
3610 -- a) The way that Determine_Range works, it will typically report
3611 -- the bounds of the value as being equal to the bounds of the
3612 -- type, because it either can't tell anything more precise, or
3613 -- does not think it is worth the effort to be more precise.
3615 -- b) It is very unusual to have a situation in which this would
3616 -- generate an unnecessary overflow check (an example would be
3617 -- a subtype with a range 0 .. Integer'Last - 1 to which the
3618 -- literal value one is added).
3620 -- c) The alternative is a lot of special casing in this routine
3621 -- which would partially duplicate Determine_Range processing.
3623 if OK
3624 and then Lo > Expr_Value (Type_Low_Bound (Typ))
3625 and then Hi < Expr_Value (Type_High_Bound (Typ))
3626 then
3627 if Debug_Flag_CC then
3628 w ("No overflow check required");
3629 end if;
3631 return;
3632 end if;
3633 end if;
3635 -- If not in optimizing mode, set flag and we are done. We are also done
3636 -- (and just set the flag) if the type is not a discrete type, since it
3637 -- is not worth the effort to eliminate checks for other than discrete
3638 -- types. In addition, we take this same path if we have stored the
3639 -- maximum number of checks possible already (a very unlikely situation,
3640 -- but we do not want to blow up!)
3642 if Optimization_Level = 0
3643 or else not Is_Discrete_Type (Etype (N))
3644 or else Num_Saved_Checks = Saved_Checks'Last
3645 then
3646 Activate_Overflow_Check (N);
3648 if Debug_Flag_CC then
3649 w ("Optimization off");
3650 end if;
3652 return;
3653 end if;
3655 -- Otherwise evaluate and check the expression
3657 Find_Check
3658 (Expr => N,
3659 Check_Type => 'O',
3660 Target_Type => Empty,
3661 Entry_OK => OK,
3662 Check_Num => Chk,
3663 Ent => Ent,
3664 Ofs => Ofs);
3666 if Debug_Flag_CC then
3667 w ("Called Find_Check");
3668 w (" OK = ", OK);
3670 if OK then
3671 w (" Check_Num = ", Chk);
3672 w (" Ent = ", Int (Ent));
3673 Write_Str (" Ofs = ");
3674 pid (Ofs);
3675 end if;
3676 end if;
3678 -- If check is not of form to optimize, then set flag and we are done
3680 if not OK then
3681 Activate_Overflow_Check (N);
3682 return;
3683 end if;
3685 -- If check is already performed, then return without setting flag
3687 if Chk /= 0 then
3688 if Debug_Flag_CC then
3689 w ("Check suppressed!");
3690 end if;
3692 return;
3693 end if;
3695 -- Here we will make a new entry for the new check
3697 Activate_Overflow_Check (N);
3698 Num_Saved_Checks := Num_Saved_Checks + 1;
3699 Saved_Checks (Num_Saved_Checks) :=
3700 (Killed => False,
3701 Entity => Ent,
3702 Offset => Ofs,
3703 Check_Type => 'O',
3704 Target_Type => Empty);
3706 if Debug_Flag_CC then
3707 w ("Make new entry, check number = ", Num_Saved_Checks);
3708 w (" Entity = ", Int (Ent));
3709 Write_Str (" Offset = ");
3710 pid (Ofs);
3711 w (" Check_Type = O");
3712 w (" Target_Type = Empty");
3713 end if;
3715 -- If we get an exception, then something went wrong, probably because of
3716 -- an error in the structure of the tree due to an incorrect program. Or it
3717 -- may be a bug in the optimization circuit. In either case the safest
3718 -- thing is simply to set the check flag unconditionally.
3720 exception
3721 when others =>
3722 Activate_Overflow_Check (N);
3724 if Debug_Flag_CC then
3725 w (" exception occurred, overflow flag set");
3726 end if;
3728 return;
3729 end Enable_Overflow_Check;
3731 ------------------------
3732 -- Enable_Range_Check --
3733 ------------------------
3735 procedure Enable_Range_Check (N : Node_Id) is
3736 Chk : Nat;
3737 OK : Boolean;
3738 Ent : Entity_Id;
3739 Ofs : Uint;
3740 Ttyp : Entity_Id;
3741 P : Node_Id;
3743 begin
3744 -- Return if unchecked type conversion with range check killed. In this
3745 -- case we never set the flag (that's what Kill_Range_Check is about!)
3747 if Nkind (N) = N_Unchecked_Type_Conversion
3748 and then Kill_Range_Check (N)
3749 then
3750 return;
3751 end if;
3753 -- Do not set range check flag if parent is assignment statement or
3754 -- object declaration with Suppress_Assignment_Checks flag set
3756 if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
3757 and then Suppress_Assignment_Checks (Parent (N))
3758 then
3759 return;
3760 end if;
3762 -- Check for various cases where we should suppress the range check
3764 -- No check if range checks suppressed for type of node
3766 if Present (Etype (N))
3767 and then Range_Checks_Suppressed (Etype (N))
3768 then
3769 return;
3771 -- No check if node is an entity name, and range checks are suppressed
3772 -- for this entity, or for the type of this entity.
3774 elsif Is_Entity_Name (N)
3775 and then (Range_Checks_Suppressed (Entity (N))
3776 or else Range_Checks_Suppressed (Etype (Entity (N))))
3777 then
3778 return;
3780 -- No checks if index of array, and index checks are suppressed for
3781 -- the array object or the type of the array.
3783 elsif Nkind (Parent (N)) = N_Indexed_Component then
3784 declare
3785 Pref : constant Node_Id := Prefix (Parent (N));
3786 begin
3787 if Is_Entity_Name (Pref)
3788 and then Index_Checks_Suppressed (Entity (Pref))
3789 then
3790 return;
3791 elsif Index_Checks_Suppressed (Etype (Pref)) then
3792 return;
3793 end if;
3794 end;
3795 end if;
3797 -- Debug trace output
3799 if Debug_Flag_CC then
3800 w ("Enable_Range_Check for node ", Int (N));
3801 Write_Str (" Source location = ");
3802 wl (Sloc (N));
3803 pg (Union_Id (N));
3804 end if;
3806 -- If not in optimizing mode, set flag and we are done. We are also done
3807 -- (and just set the flag) if the type is not a discrete type, since it
3808 -- is not worth the effort to eliminate checks for other than discrete
3809 -- types. In addition, we take this same path if we have stored the
3810 -- maximum number of checks possible already (a very unlikely situation,
3811 -- but we do not want to blow up!)
3813 if Optimization_Level = 0
3814 or else No (Etype (N))
3815 or else not Is_Discrete_Type (Etype (N))
3816 or else Num_Saved_Checks = Saved_Checks'Last
3817 then
3818 Activate_Range_Check (N);
3820 if Debug_Flag_CC then
3821 w ("Optimization off");
3822 end if;
3824 return;
3825 end if;
3827 -- Otherwise find out the target type
3829 P := Parent (N);
3831 -- For assignment, use left side subtype
3833 if Nkind (P) = N_Assignment_Statement
3834 and then Expression (P) = N
3835 then
3836 Ttyp := Etype (Name (P));
3838 -- For indexed component, use subscript subtype
3840 elsif Nkind (P) = N_Indexed_Component then
3841 declare
3842 Atyp : Entity_Id;
3843 Indx : Node_Id;
3844 Subs : Node_Id;
3846 begin
3847 Atyp := Etype (Prefix (P));
3849 if Is_Access_Type (Atyp) then
3850 Atyp := Designated_Type (Atyp);
3852 -- If the prefix is an access to an unconstrained array,
3853 -- perform check unconditionally: it depends on the bounds of
3854 -- an object and we cannot currently recognize whether the test
3855 -- may be redundant.
3857 if not Is_Constrained (Atyp) then
3858 Activate_Range_Check (N);
3859 return;
3860 end if;
3862 -- Ditto if the prefix is an explicit dereference whose designated
3863 -- type is unconstrained.
3865 elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3866 and then not Is_Constrained (Atyp)
3867 then
3868 Activate_Range_Check (N);
3869 return;
3870 end if;
3872 Indx := First_Index (Atyp);
3873 Subs := First (Expressions (P));
3874 loop
3875 if Subs = N then
3876 Ttyp := Etype (Indx);
3877 exit;
3878 end if;
3880 Next_Index (Indx);
3881 Next (Subs);
3882 end loop;
3883 end;
3885 -- For now, ignore all other cases, they are not so interesting
3887 else
3888 if Debug_Flag_CC then
3889 w (" target type not found, flag set");
3890 end if;
3892 Activate_Range_Check (N);
3893 return;
3894 end if;
3896 -- Evaluate and check the expression
3898 Find_Check
3899 (Expr => N,
3900 Check_Type => 'R',
3901 Target_Type => Ttyp,
3902 Entry_OK => OK,
3903 Check_Num => Chk,
3904 Ent => Ent,
3905 Ofs => Ofs);
3907 if Debug_Flag_CC then
3908 w ("Called Find_Check");
3909 w ("Target_Typ = ", Int (Ttyp));
3910 w (" OK = ", OK);
3912 if OK then
3913 w (" Check_Num = ", Chk);
3914 w (" Ent = ", Int (Ent));
3915 Write_Str (" Ofs = ");
3916 pid (Ofs);
3917 end if;
3918 end if;
3920 -- If check is not of form to optimize, then set flag and we are done
3922 if not OK then
3923 if Debug_Flag_CC then
3924 w (" expression not of optimizable type, flag set");
3925 end if;
3927 Activate_Range_Check (N);
3928 return;
3929 end if;
3931 -- If check is already performed, then return without setting flag
3933 if Chk /= 0 then
3934 if Debug_Flag_CC then
3935 w ("Check suppressed!");
3936 end if;
3938 return;
3939 end if;
3941 -- Here we will make a new entry for the new check
3943 Activate_Range_Check (N);
3944 Num_Saved_Checks := Num_Saved_Checks + 1;
3945 Saved_Checks (Num_Saved_Checks) :=
3946 (Killed => False,
3947 Entity => Ent,
3948 Offset => Ofs,
3949 Check_Type => 'R',
3950 Target_Type => Ttyp);
3952 if Debug_Flag_CC then
3953 w ("Make new entry, check number = ", Num_Saved_Checks);
3954 w (" Entity = ", Int (Ent));
3955 Write_Str (" Offset = ");
3956 pid (Ofs);
3957 w (" Check_Type = R");
3958 w (" Target_Type = ", Int (Ttyp));
3959 pg (Union_Id (Ttyp));
3960 end if;
3962 -- If we get an exception, then something went wrong, probably because of
3963 -- an error in the structure of the tree due to an incorrect program. Or
3964 -- it may be a bug in the optimization circuit. In either case the safest
3965 -- thing is simply to set the check flag unconditionally.
3967 exception
3968 when others =>
3969 Activate_Range_Check (N);
3971 if Debug_Flag_CC then
3972 w (" exception occurred, range flag set");
3973 end if;
3975 return;
3976 end Enable_Range_Check;
3978 ------------------
3979 -- Ensure_Valid --
3980 ------------------
3982 procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3983 Typ : constant Entity_Id := Etype (Expr);
3985 begin
3986 -- Ignore call if we are not doing any validity checking
3988 if not Validity_Checks_On then
3989 return;
3991 -- Ignore call if range or validity checks suppressed on entity or type
3993 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3994 return;
3996 -- No check required if expression is from the expander, we assume the
3997 -- expander will generate whatever checks are needed. Note that this is
3998 -- not just an optimization, it avoids infinite recursions!
4000 -- Unchecked conversions must be checked, unless they are initialized
4001 -- scalar values, as in a component assignment in an init proc.
4003 -- In addition, we force a check if Force_Validity_Checks is set
4005 elsif not Comes_From_Source (Expr)
4006 and then not Force_Validity_Checks
4007 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
4008 or else Kill_Range_Check (Expr))
4009 then
4010 return;
4012 -- No check required if expression is known to have valid value
4014 elsif Expr_Known_Valid (Expr) then
4015 return;
4017 -- Ignore case of enumeration with holes where the flag is set not to
4018 -- worry about holes, since no special validity check is needed
4020 elsif Is_Enumeration_Type (Typ)
4021 and then Has_Non_Standard_Rep (Typ)
4022 and then Holes_OK
4023 then
4024 return;
4026 -- No check required on the left-hand side of an assignment
4028 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
4029 and then Expr = Name (Parent (Expr))
4030 then
4031 return;
4033 -- No check on a universal real constant. The context will eventually
4034 -- convert it to a machine number for some target type, or report an
4035 -- illegality.
4037 elsif Nkind (Expr) = N_Real_Literal
4038 and then Etype (Expr) = Universal_Real
4039 then
4040 return;
4042 -- If the expression denotes a component of a packed boolean array,
4043 -- no possible check applies. We ignore the old ACATS chestnuts that
4044 -- involve Boolean range True..True.
4046 -- Note: validity checks are generated for expressions that yield a
4047 -- scalar type, when it is possible to create a value that is outside of
4048 -- the type. If this is a one-bit boolean no such value exists. This is
4049 -- an optimization, and it also prevents compiler blowing up during the
4050 -- elaboration of improperly expanded packed array references.
4052 elsif Nkind (Expr) = N_Indexed_Component
4053 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
4054 and then Root_Type (Etype (Expr)) = Standard_Boolean
4055 then
4056 return;
4058 -- An annoying special case. If this is an out parameter of a scalar
4059 -- type, then the value is not going to be accessed, therefore it is
4060 -- inappropriate to do any validity check at the call site.
4062 else
4063 -- Only need to worry about scalar types
4065 if Is_Scalar_Type (Typ) then
4066 declare
4067 P : Node_Id;
4068 N : Node_Id;
4069 E : Entity_Id;
4070 F : Entity_Id;
4071 A : Node_Id;
4072 L : List_Id;
4074 begin
4075 -- Find actual argument (which may be a parameter association)
4076 -- and the parent of the actual argument (the call statement)
4078 N := Expr;
4079 P := Parent (Expr);
4081 if Nkind (P) = N_Parameter_Association then
4082 N := P;
4083 P := Parent (N);
4084 end if;
4086 -- Only need to worry if we are argument of a procedure call
4087 -- since functions don't have out parameters. If this is an
4088 -- indirect or dispatching call, get signature from the
4089 -- subprogram type.
4091 if Nkind (P) = N_Procedure_Call_Statement then
4092 L := Parameter_Associations (P);
4094 if Is_Entity_Name (Name (P)) then
4095 E := Entity (Name (P));
4096 else
4097 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
4098 E := Etype (Name (P));
4099 end if;
4101 -- Only need to worry if there are indeed actuals, and if
4102 -- this could be a procedure call, otherwise we cannot get a
4103 -- match (either we are not an argument, or the mode of the
4104 -- formal is not OUT). This test also filters out the
4105 -- generic case.
4107 if Is_Non_Empty_List (L)
4108 and then Is_Subprogram (E)
4109 then
4110 -- This is the loop through parameters, looking for an
4111 -- OUT parameter for which we are the argument.
4113 F := First_Formal (E);
4114 A := First (L);
4115 while Present (F) loop
4116 if Ekind (F) = E_Out_Parameter and then A = N then
4117 return;
4118 end if;
4120 Next_Formal (F);
4121 Next (A);
4122 end loop;
4123 end if;
4124 end if;
4125 end;
4126 end if;
4127 end if;
4129 -- If this is a boolean expression, only its elementary operands need
4130 -- checking: if they are valid, a boolean or short-circuit operation
4131 -- with them will be valid as well.
4133 if Base_Type (Typ) = Standard_Boolean
4134 and then
4135 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
4136 then
4137 return;
4138 end if;
4140 -- If we fall through, a validity check is required
4142 Insert_Valid_Check (Expr);
4144 if Is_Entity_Name (Expr)
4145 and then Safe_To_Capture_Value (Expr, Entity (Expr))
4146 then
4147 Set_Is_Known_Valid (Entity (Expr));
4148 end if;
4149 end Ensure_Valid;
4151 ----------------------
4152 -- Expr_Known_Valid --
4153 ----------------------
4155 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
4156 Typ : constant Entity_Id := Etype (Expr);
4158 begin
4159 -- Non-scalar types are always considered valid, since they never give
4160 -- rise to the issues of erroneous or bounded error behavior that are
4161 -- the concern. In formal reference manual terms the notion of validity
4162 -- only applies to scalar types. Note that even when packed arrays are
4163 -- represented using modular types, they are still arrays semantically,
4164 -- so they are also always valid (in particular, the unused bits can be
4165 -- random rubbish without affecting the validity of the array value).
4167 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
4168 return True;
4170 -- If no validity checking, then everything is considered valid
4172 elsif not Validity_Checks_On then
4173 return True;
4175 -- Floating-point types are considered valid unless floating-point
4176 -- validity checks have been specifically turned on.
4178 elsif Is_Floating_Point_Type (Typ)
4179 and then not Validity_Check_Floating_Point
4180 then
4181 return True;
4183 -- If the expression is the value of an object that is known to be
4184 -- valid, then clearly the expression value itself is valid.
4186 elsif Is_Entity_Name (Expr)
4187 and then Is_Known_Valid (Entity (Expr))
4188 then
4189 return True;
4191 -- References to discriminants are always considered valid. The value
4192 -- of a discriminant gets checked when the object is built. Within the
4193 -- record, we consider it valid, and it is important to do so, since
4194 -- otherwise we can try to generate bogus validity checks which
4195 -- reference discriminants out of scope. Discriminants of concurrent
4196 -- types are excluded for the same reason.
4198 elsif Is_Entity_Name (Expr)
4199 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
4200 then
4201 return True;
4203 -- If the type is one for which all values are known valid, then we are
4204 -- sure that the value is valid except in the slightly odd case where
4205 -- the expression is a reference to a variable whose size has been
4206 -- explicitly set to a value greater than the object size.
4208 elsif Is_Known_Valid (Typ) then
4209 if Is_Entity_Name (Expr)
4210 and then Ekind (Entity (Expr)) = E_Variable
4211 and then Esize (Entity (Expr)) > Esize (Typ)
4212 then
4213 return False;
4214 else
4215 return True;
4216 end if;
4218 -- Integer and character literals always have valid values, where
4219 -- appropriate these will be range checked in any case.
4221 elsif Nkind (Expr) = N_Integer_Literal
4222 or else
4223 Nkind (Expr) = N_Character_Literal
4224 then
4225 return True;
4227 -- If we have a type conversion or a qualification of a known valid
4228 -- value, then the result will always be valid.
4230 elsif Nkind (Expr) = N_Type_Conversion
4231 or else
4232 Nkind (Expr) = N_Qualified_Expression
4233 then
4234 return Expr_Known_Valid (Expression (Expr));
4236 -- The result of any operator is always considered valid, since we
4237 -- assume the necessary checks are done by the operator. For operators
4238 -- on floating-point operations, we must also check when the operation
4239 -- is the right-hand side of an assignment, or is an actual in a call.
4241 elsif Nkind (Expr) in N_Op then
4242 if Is_Floating_Point_Type (Typ)
4243 and then Validity_Check_Floating_Point
4244 and then
4245 (Nkind (Parent (Expr)) = N_Assignment_Statement
4246 or else Nkind (Parent (Expr)) = N_Function_Call
4247 or else Nkind (Parent (Expr)) = N_Parameter_Association)
4248 then
4249 return False;
4250 else
4251 return True;
4252 end if;
4254 -- The result of a membership test is always valid, since it is true or
4255 -- false, there are no other possibilities.
4257 elsif Nkind (Expr) in N_Membership_Test then
4258 return True;
4260 -- For all other cases, we do not know the expression is valid
4262 else
4263 return False;
4264 end if;
4265 end Expr_Known_Valid;
4267 ----------------
4268 -- Find_Check --
4269 ----------------
4271 procedure Find_Check
4272 (Expr : Node_Id;
4273 Check_Type : Character;
4274 Target_Type : Entity_Id;
4275 Entry_OK : out Boolean;
4276 Check_Num : out Nat;
4277 Ent : out Entity_Id;
4278 Ofs : out Uint)
4280 function Within_Range_Of
4281 (Target_Type : Entity_Id;
4282 Check_Type : Entity_Id) return Boolean;
4283 -- Given a requirement for checking a range against Target_Type, and
4284 -- and a range Check_Type against which a check has already been made,
4285 -- determines if the check against check type is sufficient to ensure
4286 -- that no check against Target_Type is required.
4288 ---------------------
4289 -- Within_Range_Of --
4290 ---------------------
4292 function Within_Range_Of
4293 (Target_Type : Entity_Id;
4294 Check_Type : Entity_Id) return Boolean
4296 begin
4297 if Target_Type = Check_Type then
4298 return True;
4300 else
4301 declare
4302 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
4303 Thi : constant Node_Id := Type_High_Bound (Target_Type);
4304 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
4305 Chi : constant Node_Id := Type_High_Bound (Check_Type);
4307 begin
4308 if (Tlo = Clo
4309 or else (Compile_Time_Known_Value (Tlo)
4310 and then
4311 Compile_Time_Known_Value (Clo)
4312 and then
4313 Expr_Value (Clo) >= Expr_Value (Tlo)))
4314 and then
4315 (Thi = Chi
4316 or else (Compile_Time_Known_Value (Thi)
4317 and then
4318 Compile_Time_Known_Value (Chi)
4319 and then
4320 Expr_Value (Chi) <= Expr_Value (Clo)))
4321 then
4322 return True;
4323 else
4324 return False;
4325 end if;
4326 end;
4327 end if;
4328 end Within_Range_Of;
4330 -- Start of processing for Find_Check
4332 begin
4333 -- Establish default, in case no entry is found
4335 Check_Num := 0;
4337 -- Case of expression is simple entity reference
4339 if Is_Entity_Name (Expr) then
4340 Ent := Entity (Expr);
4341 Ofs := Uint_0;
4343 -- Case of expression is entity + known constant
4345 elsif Nkind (Expr) = N_Op_Add
4346 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4347 and then Is_Entity_Name (Left_Opnd (Expr))
4348 then
4349 Ent := Entity (Left_Opnd (Expr));
4350 Ofs := Expr_Value (Right_Opnd (Expr));
4352 -- Case of expression is entity - known constant
4354 elsif Nkind (Expr) = N_Op_Subtract
4355 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4356 and then Is_Entity_Name (Left_Opnd (Expr))
4357 then
4358 Ent := Entity (Left_Opnd (Expr));
4359 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4361 -- Any other expression is not of the right form
4363 else
4364 Ent := Empty;
4365 Ofs := Uint_0;
4366 Entry_OK := False;
4367 return;
4368 end if;
4370 -- Come here with expression of appropriate form, check if entity is an
4371 -- appropriate one for our purposes.
4373 if (Ekind (Ent) = E_Variable
4374 or else Is_Constant_Object (Ent))
4375 and then not Is_Library_Level_Entity (Ent)
4376 then
4377 Entry_OK := True;
4378 else
4379 Entry_OK := False;
4380 return;
4381 end if;
4383 -- See if there is matching check already
4385 for J in reverse 1 .. Num_Saved_Checks loop
4386 declare
4387 SC : Saved_Check renames Saved_Checks (J);
4389 begin
4390 if SC.Killed = False
4391 and then SC.Entity = Ent
4392 and then SC.Offset = Ofs
4393 and then SC.Check_Type = Check_Type
4394 and then Within_Range_Of (Target_Type, SC.Target_Type)
4395 then
4396 Check_Num := J;
4397 return;
4398 end if;
4399 end;
4400 end loop;
4402 -- If we fall through entry was not found
4404 return;
4405 end Find_Check;
4407 ---------------------------------
4408 -- Generate_Discriminant_Check --
4409 ---------------------------------
4411 -- Note: the code for this procedure is derived from the
4412 -- Emit_Discriminant_Check Routine in trans.c.
4414 procedure Generate_Discriminant_Check (N : Node_Id) is
4415 Loc : constant Source_Ptr := Sloc (N);
4416 Pref : constant Node_Id := Prefix (N);
4417 Sel : constant Node_Id := Selector_Name (N);
4419 Orig_Comp : constant Entity_Id :=
4420 Original_Record_Component (Entity (Sel));
4421 -- The original component to be checked
4423 Discr_Fct : constant Entity_Id :=
4424 Discriminant_Checking_Func (Orig_Comp);
4425 -- The discriminant checking function
4427 Discr : Entity_Id;
4428 -- One discriminant to be checked in the type
4430 Real_Discr : Entity_Id;
4431 -- Actual discriminant in the call
4433 Pref_Type : Entity_Id;
4434 -- Type of relevant prefix (ignoring private/access stuff)
4436 Args : List_Id;
4437 -- List of arguments for function call
4439 Formal : Entity_Id;
4440 -- Keep track of the formal corresponding to the actual we build for
4441 -- each discriminant, in order to be able to perform the necessary type
4442 -- conversions.
4444 Scomp : Node_Id;
4445 -- Selected component reference for checking function argument
4447 begin
4448 Pref_Type := Etype (Pref);
4450 -- Force evaluation of the prefix, so that it does not get evaluated
4451 -- twice (once for the check, once for the actual reference). Such a
4452 -- double evaluation is always a potential source of inefficiency,
4453 -- and is functionally incorrect in the volatile case, or when the
4454 -- prefix may have side-effects. An entity or a component of an
4455 -- entity requires no evaluation.
4457 if Is_Entity_Name (Pref) then
4458 if Treat_As_Volatile (Entity (Pref)) then
4459 Force_Evaluation (Pref, Name_Req => True);
4460 end if;
4462 elsif Treat_As_Volatile (Etype (Pref)) then
4463 Force_Evaluation (Pref, Name_Req => True);
4465 elsif Nkind (Pref) = N_Selected_Component
4466 and then Is_Entity_Name (Prefix (Pref))
4467 then
4468 null;
4470 else
4471 Force_Evaluation (Pref, Name_Req => True);
4472 end if;
4474 -- For a tagged type, use the scope of the original component to
4475 -- obtain the type, because ???
4477 if Is_Tagged_Type (Scope (Orig_Comp)) then
4478 Pref_Type := Scope (Orig_Comp);
4480 -- For an untagged derived type, use the discriminants of the parent
4481 -- which have been renamed in the derivation, possibly by a one-to-many
4482 -- discriminant constraint. For non-tagged type, initially get the Etype
4483 -- of the prefix
4485 else
4486 if Is_Derived_Type (Pref_Type)
4487 and then Number_Discriminants (Pref_Type) /=
4488 Number_Discriminants (Etype (Base_Type (Pref_Type)))
4489 then
4490 Pref_Type := Etype (Base_Type (Pref_Type));
4491 end if;
4492 end if;
4494 -- We definitely should have a checking function, This routine should
4495 -- not be called if no discriminant checking function is present.
4497 pragma Assert (Present (Discr_Fct));
4499 -- Create the list of the actual parameters for the call. This list
4500 -- is the list of the discriminant fields of the record expression to
4501 -- be discriminant checked.
4503 Args := New_List;
4504 Formal := First_Formal (Discr_Fct);
4505 Discr := First_Discriminant (Pref_Type);
4506 while Present (Discr) loop
4508 -- If we have a corresponding discriminant field, and a parent
4509 -- subtype is present, then we want to use the corresponding
4510 -- discriminant since this is the one with the useful value.
4512 if Present (Corresponding_Discriminant (Discr))
4513 and then Ekind (Pref_Type) = E_Record_Type
4514 and then Present (Parent_Subtype (Pref_Type))
4515 then
4516 Real_Discr := Corresponding_Discriminant (Discr);
4517 else
4518 Real_Discr := Discr;
4519 end if;
4521 -- Construct the reference to the discriminant
4523 Scomp :=
4524 Make_Selected_Component (Loc,
4525 Prefix =>
4526 Unchecked_Convert_To (Pref_Type,
4527 Duplicate_Subexpr (Pref)),
4528 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4530 -- Manually analyze and resolve this selected component. We really
4531 -- want it just as it appears above, and do not want the expander
4532 -- playing discriminal games etc with this reference. Then we append
4533 -- the argument to the list we are gathering.
4535 Set_Etype (Scomp, Etype (Real_Discr));
4536 Set_Analyzed (Scomp, True);
4537 Append_To (Args, Convert_To (Etype (Formal), Scomp));
4539 Next_Formal_With_Extras (Formal);
4540 Next_Discriminant (Discr);
4541 end loop;
4543 -- Now build and insert the call
4545 Insert_Action (N,
4546 Make_Raise_Constraint_Error (Loc,
4547 Condition =>
4548 Make_Function_Call (Loc,
4549 Name => New_Occurrence_Of (Discr_Fct, Loc),
4550 Parameter_Associations => Args),
4551 Reason => CE_Discriminant_Check_Failed));
4552 end Generate_Discriminant_Check;
4554 ---------------------------
4555 -- Generate_Index_Checks --
4556 ---------------------------
4558 procedure Generate_Index_Checks (N : Node_Id) is
4559 Loc : constant Source_Ptr := Sloc (N);
4560 A : constant Node_Id := Prefix (N);
4561 Sub : Node_Id;
4562 Ind : Nat;
4563 Num : List_Id;
4565 begin
4566 -- Ignore call if index checks suppressed for array object or type
4568 if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4569 or else Index_Checks_Suppressed (Etype (A))
4570 then
4571 return;
4572 end if;
4574 -- Generate the checks
4576 Sub := First (Expressions (N));
4577 Ind := 1;
4578 while Present (Sub) loop
4579 if Do_Range_Check (Sub) then
4580 Set_Do_Range_Check (Sub, False);
4582 -- Force evaluation except for the case of a simple name of a
4583 -- non-volatile entity.
4585 if not Is_Entity_Name (Sub)
4586 or else Treat_As_Volatile (Entity (Sub))
4587 then
4588 Force_Evaluation (Sub);
4589 end if;
4591 -- Generate a raise of constraint error with the appropriate
4592 -- reason and a condition of the form:
4594 -- Base_Type(Sub) not in array'range (subscript)
4596 -- Note that the reason we generate the conversion to the base
4597 -- type here is that we definitely want the range check to take
4598 -- place, even if it looks like the subtype is OK. Optimization
4599 -- considerations that allow us to omit the check have already
4600 -- been taken into account in the setting of the Do_Range_Check
4601 -- flag earlier on.
4603 if Ind = 1 then
4604 Num := No_List;
4605 else
4606 Num := New_List (Make_Integer_Literal (Loc, Ind));
4607 end if;
4609 Insert_Action (N,
4610 Make_Raise_Constraint_Error (Loc,
4611 Condition =>
4612 Make_Not_In (Loc,
4613 Left_Opnd =>
4614 Convert_To (Base_Type (Etype (Sub)),
4615 Duplicate_Subexpr_Move_Checks (Sub)),
4616 Right_Opnd =>
4617 Make_Attribute_Reference (Loc,
4618 Prefix =>
4619 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
4620 Attribute_Name => Name_Range,
4621 Expressions => Num)),
4622 Reason => CE_Index_Check_Failed));
4623 end if;
4625 Ind := Ind + 1;
4626 Next (Sub);
4627 end loop;
4628 end Generate_Index_Checks;
4630 --------------------------
4631 -- Generate_Range_Check --
4632 --------------------------
4634 procedure Generate_Range_Check
4635 (N : Node_Id;
4636 Target_Type : Entity_Id;
4637 Reason : RT_Exception_Code)
4639 Loc : constant Source_Ptr := Sloc (N);
4640 Source_Type : constant Entity_Id := Etype (N);
4641 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
4642 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
4644 begin
4645 -- First special case, if the source type is already within the range
4646 -- of the target type, then no check is needed (probably we should have
4647 -- stopped Do_Range_Check from being set in the first place, but better
4648 -- late than later in preventing junk code!
4650 -- We do NOT apply this if the source node is a literal, since in this
4651 -- case the literal has already been labeled as having the subtype of
4652 -- the target.
4654 if In_Subrange_Of (Source_Type, Target_Type)
4655 and then not
4656 (Nkind (N) = N_Integer_Literal
4657 or else
4658 Nkind (N) = N_Real_Literal
4659 or else
4660 Nkind (N) = N_Character_Literal
4661 or else
4662 (Is_Entity_Name (N)
4663 and then Ekind (Entity (N)) = E_Enumeration_Literal))
4664 then
4665 return;
4666 end if;
4668 -- We need a check, so force evaluation of the node, so that it does
4669 -- not get evaluated twice (once for the check, once for the actual
4670 -- reference). Such a double evaluation is always a potential source
4671 -- of inefficiency, and is functionally incorrect in the volatile case.
4673 if not Is_Entity_Name (N)
4674 or else Treat_As_Volatile (Entity (N))
4675 then
4676 Force_Evaluation (N);
4677 end if;
4679 -- The easiest case is when Source_Base_Type and Target_Base_Type are
4680 -- the same since in this case we can simply do a direct check of the
4681 -- value of N against the bounds of Target_Type.
4683 -- [constraint_error when N not in Target_Type]
4685 -- Note: this is by far the most common case, for example all cases of
4686 -- checks on the RHS of assignments are in this category, but not all
4687 -- cases are like this. Notably conversions can involve two types.
4689 if Source_Base_Type = Target_Base_Type then
4690 Insert_Action (N,
4691 Make_Raise_Constraint_Error (Loc,
4692 Condition =>
4693 Make_Not_In (Loc,
4694 Left_Opnd => Duplicate_Subexpr (N),
4695 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4696 Reason => Reason));
4698 -- Next test for the case where the target type is within the bounds
4699 -- of the base type of the source type, since in this case we can
4700 -- simply convert these bounds to the base type of T to do the test.
4702 -- [constraint_error when N not in
4703 -- Source_Base_Type (Target_Type'First)
4704 -- ..
4705 -- Source_Base_Type(Target_Type'Last))]
4707 -- The conversions will always work and need no check
4709 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
4710 -- of converting from an enumeration value to an integer type, such as
4711 -- occurs for the case of generating a range check on Enum'Val(Exp)
4712 -- (which used to be handled by gigi). This is OK, since the conversion
4713 -- itself does not require a check.
4715 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4716 Insert_Action (N,
4717 Make_Raise_Constraint_Error (Loc,
4718 Condition =>
4719 Make_Not_In (Loc,
4720 Left_Opnd => Duplicate_Subexpr (N),
4722 Right_Opnd =>
4723 Make_Range (Loc,
4724 Low_Bound =>
4725 Unchecked_Convert_To (Source_Base_Type,
4726 Make_Attribute_Reference (Loc,
4727 Prefix =>
4728 New_Occurrence_Of (Target_Type, Loc),
4729 Attribute_Name => Name_First)),
4731 High_Bound =>
4732 Unchecked_Convert_To (Source_Base_Type,
4733 Make_Attribute_Reference (Loc,
4734 Prefix =>
4735 New_Occurrence_Of (Target_Type, Loc),
4736 Attribute_Name => Name_Last)))),
4737 Reason => Reason));
4739 -- Note that at this stage we now that the Target_Base_Type is not in
4740 -- the range of the Source_Base_Type (since even the Target_Type itself
4741 -- is not in this range). It could still be the case that Source_Type is
4742 -- in range of the target base type since we have not checked that case.
4744 -- If that is the case, we can freely convert the source to the target,
4745 -- and then test the target result against the bounds.
4747 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4749 -- We make a temporary to hold the value of the converted value
4750 -- (converted to the base type), and then we will do the test against
4751 -- this temporary.
4753 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
4754 -- [constraint_error when Tnn not in Target_Type]
4756 -- Then the conversion itself is replaced by an occurrence of Tnn
4758 declare
4759 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4761 begin
4762 Insert_Actions (N, New_List (
4763 Make_Object_Declaration (Loc,
4764 Defining_Identifier => Tnn,
4765 Object_Definition =>
4766 New_Occurrence_Of (Target_Base_Type, Loc),
4767 Constant_Present => True,
4768 Expression =>
4769 Make_Type_Conversion (Loc,
4770 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4771 Expression => Duplicate_Subexpr (N))),
4773 Make_Raise_Constraint_Error (Loc,
4774 Condition =>
4775 Make_Not_In (Loc,
4776 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4777 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4779 Reason => Reason)));
4781 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4783 -- Set the type of N, because the declaration for Tnn might not
4784 -- be analyzed yet, as is the case if N appears within a record
4785 -- declaration, as a discriminant constraint or expression.
4787 Set_Etype (N, Target_Base_Type);
4788 end;
4790 -- At this stage, we know that we have two scalar types, which are
4791 -- directly convertible, and where neither scalar type has a base
4792 -- range that is in the range of the other scalar type.
4794 -- The only way this can happen is with a signed and unsigned type.
4795 -- So test for these two cases:
4797 else
4798 -- Case of the source is unsigned and the target is signed
4800 if Is_Unsigned_Type (Source_Base_Type)
4801 and then not Is_Unsigned_Type (Target_Base_Type)
4802 then
4803 -- If the source is unsigned and the target is signed, then we
4804 -- know that the source is not shorter than the target (otherwise
4805 -- the source base type would be in the target base type range).
4807 -- In other words, the unsigned type is either the same size as
4808 -- the target, or it is larger. It cannot be smaller.
4810 pragma Assert
4811 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4813 -- We only need to check the low bound if the low bound of the
4814 -- target type is non-negative. If the low bound of the target
4815 -- type is negative, then we know that we will fit fine.
4817 -- If the high bound of the target type is negative, then we
4818 -- know we have a constraint error, since we can't possibly
4819 -- have a negative source.
4821 -- With these two checks out of the way, we can do the check
4822 -- using the source type safely
4824 -- This is definitely the most annoying case!
4826 -- [constraint_error
4827 -- when (Target_Type'First >= 0
4828 -- and then
4829 -- N < Source_Base_Type (Target_Type'First))
4830 -- or else Target_Type'Last < 0
4831 -- or else N > Source_Base_Type (Target_Type'Last)];
4833 -- We turn off all checks since we know that the conversions
4834 -- will work fine, given the guards for negative values.
4836 Insert_Action (N,
4837 Make_Raise_Constraint_Error (Loc,
4838 Condition =>
4839 Make_Or_Else (Loc,
4840 Make_Or_Else (Loc,
4841 Left_Opnd =>
4842 Make_And_Then (Loc,
4843 Left_Opnd => Make_Op_Ge (Loc,
4844 Left_Opnd =>
4845 Make_Attribute_Reference (Loc,
4846 Prefix =>
4847 New_Occurrence_Of (Target_Type, Loc),
4848 Attribute_Name => Name_First),
4849 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4851 Right_Opnd =>
4852 Make_Op_Lt (Loc,
4853 Left_Opnd => Duplicate_Subexpr (N),
4854 Right_Opnd =>
4855 Convert_To (Source_Base_Type,
4856 Make_Attribute_Reference (Loc,
4857 Prefix =>
4858 New_Occurrence_Of (Target_Type, Loc),
4859 Attribute_Name => Name_First)))),
4861 Right_Opnd =>
4862 Make_Op_Lt (Loc,
4863 Left_Opnd =>
4864 Make_Attribute_Reference (Loc,
4865 Prefix => New_Occurrence_Of (Target_Type, Loc),
4866 Attribute_Name => Name_Last),
4867 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4869 Right_Opnd =>
4870 Make_Op_Gt (Loc,
4871 Left_Opnd => Duplicate_Subexpr (N),
4872 Right_Opnd =>
4873 Convert_To (Source_Base_Type,
4874 Make_Attribute_Reference (Loc,
4875 Prefix => New_Occurrence_Of (Target_Type, Loc),
4876 Attribute_Name => Name_Last)))),
4878 Reason => Reason),
4879 Suppress => All_Checks);
4881 -- Only remaining possibility is that the source is signed and
4882 -- the target is unsigned.
4884 else
4885 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4886 and then Is_Unsigned_Type (Target_Base_Type));
4888 -- If the source is signed and the target is unsigned, then we
4889 -- know that the target is not shorter than the source (otherwise
4890 -- the target base type would be in the source base type range).
4892 -- In other words, the unsigned type is either the same size as
4893 -- the target, or it is larger. It cannot be smaller.
4895 -- Clearly we have an error if the source value is negative since
4896 -- no unsigned type can have negative values. If the source type
4897 -- is non-negative, then the check can be done using the target
4898 -- type.
4900 -- Tnn : constant Target_Base_Type (N) := Target_Type;
4902 -- [constraint_error
4903 -- when N < 0 or else Tnn not in Target_Type];
4905 -- We turn off all checks for the conversion of N to the target
4906 -- base type, since we generate the explicit check to ensure that
4907 -- the value is non-negative
4909 declare
4910 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4912 begin
4913 Insert_Actions (N, New_List (
4914 Make_Object_Declaration (Loc,
4915 Defining_Identifier => Tnn,
4916 Object_Definition =>
4917 New_Occurrence_Of (Target_Base_Type, Loc),
4918 Constant_Present => True,
4919 Expression =>
4920 Make_Unchecked_Type_Conversion (Loc,
4921 Subtype_Mark =>
4922 New_Occurrence_Of (Target_Base_Type, Loc),
4923 Expression => Duplicate_Subexpr (N))),
4925 Make_Raise_Constraint_Error (Loc,
4926 Condition =>
4927 Make_Or_Else (Loc,
4928 Left_Opnd =>
4929 Make_Op_Lt (Loc,
4930 Left_Opnd => Duplicate_Subexpr (N),
4931 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4933 Right_Opnd =>
4934 Make_Not_In (Loc,
4935 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4936 Right_Opnd =>
4937 New_Occurrence_Of (Target_Type, Loc))),
4939 Reason => Reason)),
4940 Suppress => All_Checks);
4942 -- Set the Etype explicitly, because Insert_Actions may have
4943 -- placed the declaration in the freeze list for an enclosing
4944 -- construct, and thus it is not analyzed yet.
4946 Set_Etype (Tnn, Target_Base_Type);
4947 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4948 end;
4949 end if;
4950 end if;
4951 end Generate_Range_Check;
4953 ------------------
4954 -- Get_Check_Id --
4955 ------------------
4957 function Get_Check_Id (N : Name_Id) return Check_Id is
4958 begin
4959 -- For standard check name, we can do a direct computation
4961 if N in First_Check_Name .. Last_Check_Name then
4962 return Check_Id (N - (First_Check_Name - 1));
4964 -- For non-standard names added by pragma Check_Name, search table
4966 else
4967 for J in All_Checks + 1 .. Check_Names.Last loop
4968 if Check_Names.Table (J) = N then
4969 return J;
4970 end if;
4971 end loop;
4972 end if;
4974 -- No matching name found
4976 return No_Check_Id;
4977 end Get_Check_Id;
4979 ---------------------
4980 -- Get_Discriminal --
4981 ---------------------
4983 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4984 Loc : constant Source_Ptr := Sloc (E);
4985 D : Entity_Id;
4986 Sc : Entity_Id;
4988 begin
4989 -- The bound can be a bona fide parameter of a protected operation,
4990 -- rather than a prival encoded as an in-parameter.
4992 if No (Discriminal_Link (Entity (Bound))) then
4993 return Bound;
4994 end if;
4996 -- Climb the scope stack looking for an enclosing protected type. If
4997 -- we run out of scopes, return the bound itself.
4999 Sc := Scope (E);
5000 while Present (Sc) loop
5001 if Sc = Standard_Standard then
5002 return Bound;
5004 elsif Ekind (Sc) = E_Protected_Type then
5005 exit;
5006 end if;
5008 Sc := Scope (Sc);
5009 end loop;
5011 D := First_Discriminant (Sc);
5012 while Present (D) loop
5013 if Chars (D) = Chars (Bound) then
5014 return New_Occurrence_Of (Discriminal (D), Loc);
5015 end if;
5017 Next_Discriminant (D);
5018 end loop;
5020 return Bound;
5021 end Get_Discriminal;
5023 ----------------------
5024 -- Get_Range_Checks --
5025 ----------------------
5027 function Get_Range_Checks
5028 (Ck_Node : Node_Id;
5029 Target_Typ : Entity_Id;
5030 Source_Typ : Entity_Id := Empty;
5031 Warn_Node : Node_Id := Empty) return Check_Result
5033 begin
5034 return Selected_Range_Checks
5035 (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
5036 end Get_Range_Checks;
5038 ------------------
5039 -- Guard_Access --
5040 ------------------
5042 function Guard_Access
5043 (Cond : Node_Id;
5044 Loc : Source_Ptr;
5045 Ck_Node : Node_Id) return Node_Id
5047 begin
5048 if Nkind (Cond) = N_Or_Else then
5049 Set_Paren_Count (Cond, 1);
5050 end if;
5052 if Nkind (Ck_Node) = N_Allocator then
5053 return Cond;
5054 else
5055 return
5056 Make_And_Then (Loc,
5057 Left_Opnd =>
5058 Make_Op_Ne (Loc,
5059 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
5060 Right_Opnd => Make_Null (Loc)),
5061 Right_Opnd => Cond);
5062 end if;
5063 end Guard_Access;
5065 -----------------------------
5066 -- Index_Checks_Suppressed --
5067 -----------------------------
5069 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
5070 begin
5071 if Present (E) and then Checks_May_Be_Suppressed (E) then
5072 return Is_Check_Suppressed (E, Index_Check);
5073 else
5074 return Scope_Suppress (Index_Check);
5075 end if;
5076 end Index_Checks_Suppressed;
5078 ----------------
5079 -- Initialize --
5080 ----------------
5082 procedure Initialize is
5083 begin
5084 for J in Determine_Range_Cache_N'Range loop
5085 Determine_Range_Cache_N (J) := Empty;
5086 end loop;
5088 Check_Names.Init;
5090 for J in Int range 1 .. All_Checks loop
5091 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
5092 end loop;
5093 end Initialize;
5095 -------------------------
5096 -- Insert_Range_Checks --
5097 -------------------------
5099 procedure Insert_Range_Checks
5100 (Checks : Check_Result;
5101 Node : Node_Id;
5102 Suppress_Typ : Entity_Id;
5103 Static_Sloc : Source_Ptr := No_Location;
5104 Flag_Node : Node_Id := Empty;
5105 Do_Before : Boolean := False)
5107 Internal_Flag_Node : Node_Id := Flag_Node;
5108 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
5110 Check_Node : Node_Id;
5111 Checks_On : constant Boolean :=
5112 (not Index_Checks_Suppressed (Suppress_Typ))
5113 or else
5114 (not Range_Checks_Suppressed (Suppress_Typ));
5116 begin
5117 -- For now we just return if Checks_On is false, however this should be
5118 -- enhanced to check for an always True value in the condition and to
5119 -- generate a compilation warning???
5121 if not Expander_Active or else not Checks_On then
5122 return;
5123 end if;
5125 if Static_Sloc = No_Location then
5126 Internal_Static_Sloc := Sloc (Node);
5127 end if;
5129 if No (Flag_Node) then
5130 Internal_Flag_Node := Node;
5131 end if;
5133 for J in 1 .. 2 loop
5134 exit when No (Checks (J));
5136 if Nkind (Checks (J)) = N_Raise_Constraint_Error
5137 and then Present (Condition (Checks (J)))
5138 then
5139 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
5140 Check_Node := Checks (J);
5141 Mark_Rewrite_Insertion (Check_Node);
5143 if Do_Before then
5144 Insert_Before_And_Analyze (Node, Check_Node);
5145 else
5146 Insert_After_And_Analyze (Node, Check_Node);
5147 end if;
5149 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
5150 end if;
5152 else
5153 Check_Node :=
5154 Make_Raise_Constraint_Error (Internal_Static_Sloc,
5155 Reason => CE_Range_Check_Failed);
5156 Mark_Rewrite_Insertion (Check_Node);
5158 if Do_Before then
5159 Insert_Before_And_Analyze (Node, Check_Node);
5160 else
5161 Insert_After_And_Analyze (Node, Check_Node);
5162 end if;
5163 end if;
5164 end loop;
5165 end Insert_Range_Checks;
5167 ------------------------
5168 -- Insert_Valid_Check --
5169 ------------------------
5171 procedure Insert_Valid_Check (Expr : Node_Id) is
5172 Loc : constant Source_Ptr := Sloc (Expr);
5173 Exp : Node_Id;
5175 begin
5176 -- Do not insert if checks off, or if not checking validity or
5177 -- if expression is known to be valid
5179 if not Validity_Checks_On
5180 or else Range_Or_Validity_Checks_Suppressed (Expr)
5181 or else Expr_Known_Valid (Expr)
5182 then
5183 return;
5184 end if;
5186 -- If we have a checked conversion, then validity check applies to
5187 -- the expression inside the conversion, not the result, since if
5188 -- the expression inside is valid, then so is the conversion result.
5190 Exp := Expr;
5191 while Nkind (Exp) = N_Type_Conversion loop
5192 Exp := Expression (Exp);
5193 end loop;
5195 -- We are about to insert the validity check for Exp. We save and
5196 -- reset the Do_Range_Check flag over this validity check, and then
5197 -- put it back for the final original reference (Exp may be rewritten).
5199 declare
5200 DRC : constant Boolean := Do_Range_Check (Exp);
5202 begin
5203 Set_Do_Range_Check (Exp, False);
5205 -- Force evaluation to avoid multiple reads for atomic/volatile
5207 if Is_Entity_Name (Exp)
5208 and then Is_Volatile (Entity (Exp))
5209 then
5210 Force_Evaluation (Exp, Name_Req => True);
5211 end if;
5213 -- Insert the validity check. Note that we do this with validity
5214 -- checks turned off, to avoid recursion, we do not want validity
5215 -- checks on the validity checking code itself!
5217 Insert_Action
5218 (Expr,
5219 Make_Raise_Constraint_Error (Loc,
5220 Condition =>
5221 Make_Op_Not (Loc,
5222 Right_Opnd =>
5223 Make_Attribute_Reference (Loc,
5224 Prefix =>
5225 Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
5226 Attribute_Name => Name_Valid)),
5227 Reason => CE_Invalid_Data),
5228 Suppress => Validity_Check);
5230 -- If the expression is a reference to an element of a bit-packed
5231 -- array, then it is rewritten as a renaming declaration. If the
5232 -- expression is an actual in a call, it has not been expanded,
5233 -- waiting for the proper point at which to do it. The same happens
5234 -- with renamings, so that we have to force the expansion now. This
5235 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
5236 -- and exp_ch6.adb.
5238 if Is_Entity_Name (Exp)
5239 and then Nkind (Parent (Entity (Exp))) =
5240 N_Object_Renaming_Declaration
5241 then
5242 declare
5243 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
5244 begin
5245 if Nkind (Old_Exp) = N_Indexed_Component
5246 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
5247 then
5248 Expand_Packed_Element_Reference (Old_Exp);
5249 end if;
5250 end;
5251 end if;
5253 -- Put back the Do_Range_Check flag on the resulting (possibly
5254 -- rewritten) expression.
5256 -- Note: it might be thought that a validity check is not required
5257 -- when a range check is present, but that's not the case, because
5258 -- the back end is allowed to assume for the range check that the
5259 -- operand is within its declared range (an assumption that validity
5260 -- checking is all about NOT assuming!)
5262 -- Note: no need to worry about Possible_Local_Raise here, it will
5263 -- already have been called if original node has Do_Range_Check set.
5265 Set_Do_Range_Check (Exp, DRC);
5266 end;
5267 end Insert_Valid_Check;
5269 ----------------------------------
5270 -- Install_Null_Excluding_Check --
5271 ----------------------------------
5273 procedure Install_Null_Excluding_Check (N : Node_Id) is
5274 Loc : constant Source_Ptr := Sloc (Parent (N));
5275 Typ : constant Entity_Id := Etype (N);
5277 function Safe_To_Capture_In_Parameter_Value return Boolean;
5278 -- Determines if it is safe to capture Known_Non_Null status for an
5279 -- the entity referenced by node N. The caller ensures that N is indeed
5280 -- an entity name. It is safe to capture the non-null status for an IN
5281 -- parameter when the reference occurs within a declaration that is sure
5282 -- to be executed as part of the declarative region.
5284 procedure Mark_Non_Null;
5285 -- After installation of check, if the node in question is an entity
5286 -- name, then mark this entity as non-null if possible.
5288 function Safe_To_Capture_In_Parameter_Value return Boolean is
5289 E : constant Entity_Id := Entity (N);
5290 S : constant Entity_Id := Current_Scope;
5291 S_Par : Node_Id;
5293 begin
5294 if Ekind (E) /= E_In_Parameter then
5295 return False;
5296 end if;
5298 -- Two initial context checks. We must be inside a subprogram body
5299 -- with declarations and reference must not appear in nested scopes.
5301 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
5302 or else Scope (E) /= S
5303 then
5304 return False;
5305 end if;
5307 S_Par := Parent (Parent (S));
5309 if Nkind (S_Par) /= N_Subprogram_Body
5310 or else No (Declarations (S_Par))
5311 then
5312 return False;
5313 end if;
5315 declare
5316 N_Decl : Node_Id;
5317 P : Node_Id;
5319 begin
5320 -- Retrieve the declaration node of N (if any). Note that N
5321 -- may be a part of a complex initialization expression.
5323 P := Parent (N);
5324 N_Decl := Empty;
5325 while Present (P) loop
5327 -- If we have a short circuit form, and we are within the right
5328 -- hand expression, we return false, since the right hand side
5329 -- is not guaranteed to be elaborated.
5331 if Nkind (P) in N_Short_Circuit
5332 and then N = Right_Opnd (P)
5333 then
5334 return False;
5335 end if;
5337 -- Similarly, if we are in a conditional expression and not
5338 -- part of the condition, then we return False, since neither
5339 -- the THEN or ELSE expressions will always be elaborated.
5341 if Nkind (P) = N_Conditional_Expression
5342 and then N /= First (Expressions (P))
5343 then
5344 return False;
5345 end if;
5347 -- If we are in a case expression, and not part of the
5348 -- expression, then we return False, since a particular
5349 -- branch may not always be elaborated
5351 if Nkind (P) = N_Case_Expression
5352 and then N /= Expression (P)
5353 then
5354 return False;
5355 end if;
5357 -- While traversing the parent chain, we find that N
5358 -- belongs to a statement, thus it may never appear in
5359 -- a declarative region.
5361 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5362 or else Nkind (P) = N_Procedure_Call_Statement
5363 then
5364 return False;
5365 end if;
5367 -- If we are at a declaration, record it and exit
5369 if Nkind (P) in N_Declaration
5370 and then Nkind (P) not in N_Subprogram_Specification
5371 then
5372 N_Decl := P;
5373 exit;
5374 end if;
5376 P := Parent (P);
5377 end loop;
5379 if No (N_Decl) then
5380 return False;
5381 end if;
5383 return List_Containing (N_Decl) = Declarations (S_Par);
5384 end;
5385 end Safe_To_Capture_In_Parameter_Value;
5387 -------------------
5388 -- Mark_Non_Null --
5389 -------------------
5391 procedure Mark_Non_Null is
5392 begin
5393 -- Only case of interest is if node N is an entity name
5395 if Is_Entity_Name (N) then
5397 -- For sure, we want to clear an indication that this is known to
5398 -- be null, since if we get past this check, it definitely is not!
5400 Set_Is_Known_Null (Entity (N), False);
5402 -- We can mark the entity as known to be non-null if either it is
5403 -- safe to capture the value, or in the case of an IN parameter,
5404 -- which is a constant, if the check we just installed is in the
5405 -- declarative region of the subprogram body. In this latter case,
5406 -- a check is decisive for the rest of the body if the expression
5407 -- is sure to be elaborated, since we know we have to elaborate
5408 -- all declarations before executing the body.
5410 -- Couldn't this always be part of Safe_To_Capture_Value ???
5412 if Safe_To_Capture_Value (N, Entity (N))
5413 or else Safe_To_Capture_In_Parameter_Value
5414 then
5415 Set_Is_Known_Non_Null (Entity (N));
5416 end if;
5417 end if;
5418 end Mark_Non_Null;
5420 -- Start of processing for Install_Null_Excluding_Check
5422 begin
5423 pragma Assert (Is_Access_Type (Typ));
5425 -- No check inside a generic (why not???)
5427 if Inside_A_Generic then
5428 return;
5429 end if;
5431 -- No check needed if known to be non-null
5433 if Known_Non_Null (N) then
5434 return;
5435 end if;
5437 -- If known to be null, here is where we generate a compile time check
5439 if Known_Null (N) then
5441 -- Avoid generating warning message inside init procs
5443 if not Inside_Init_Proc then
5444 Apply_Compile_Time_Constraint_Error
5446 "null value not allowed here?",
5447 CE_Access_Check_Failed);
5448 else
5449 Insert_Action (N,
5450 Make_Raise_Constraint_Error (Loc,
5451 Reason => CE_Access_Check_Failed));
5452 end if;
5454 Mark_Non_Null;
5455 return;
5456 end if;
5458 -- If entity is never assigned, for sure a warning is appropriate
5460 if Is_Entity_Name (N) then
5461 Check_Unset_Reference (N);
5462 end if;
5464 -- No check needed if checks are suppressed on the range. Note that we
5465 -- don't set Is_Known_Non_Null in this case (we could legitimately do
5466 -- so, since the program is erroneous, but we don't like to casually
5467 -- propagate such conclusions from erroneosity).
5469 if Access_Checks_Suppressed (Typ) then
5470 return;
5471 end if;
5473 -- No check needed for access to concurrent record types generated by
5474 -- the expander. This is not just an optimization (though it does indeed
5475 -- remove junk checks). It also avoids generation of junk warnings.
5477 if Nkind (N) in N_Has_Chars
5478 and then Chars (N) = Name_uObject
5479 and then Is_Concurrent_Record_Type
5480 (Directly_Designated_Type (Etype (N)))
5481 then
5482 return;
5483 end if;
5485 -- Otherwise install access check
5487 Insert_Action (N,
5488 Make_Raise_Constraint_Error (Loc,
5489 Condition =>
5490 Make_Op_Eq (Loc,
5491 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
5492 Right_Opnd => Make_Null (Loc)),
5493 Reason => CE_Access_Check_Failed));
5495 Mark_Non_Null;
5496 end Install_Null_Excluding_Check;
5498 --------------------------
5499 -- Install_Static_Check --
5500 --------------------------
5502 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5503 Stat : constant Boolean := Is_Static_Expression (R_Cno);
5504 Typ : constant Entity_Id := Etype (R_Cno);
5506 begin
5507 Rewrite (R_Cno,
5508 Make_Raise_Constraint_Error (Loc,
5509 Reason => CE_Range_Check_Failed));
5510 Set_Analyzed (R_Cno);
5511 Set_Etype (R_Cno, Typ);
5512 Set_Raises_Constraint_Error (R_Cno);
5513 Set_Is_Static_Expression (R_Cno, Stat);
5515 -- Now deal with possible local raise handling
5517 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
5518 end Install_Static_Check;
5520 ---------------------
5521 -- Kill_All_Checks --
5522 ---------------------
5524 procedure Kill_All_Checks is
5525 begin
5526 if Debug_Flag_CC then
5527 w ("Kill_All_Checks");
5528 end if;
5530 -- We reset the number of saved checks to zero, and also modify all
5531 -- stack entries for statement ranges to indicate that the number of
5532 -- checks at each level is now zero.
5534 Num_Saved_Checks := 0;
5536 -- Note: the Int'Min here avoids any possibility of J being out of
5537 -- range when called from e.g. Conditional_Statements_Begin.
5539 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
5540 Saved_Checks_Stack (J) := 0;
5541 end loop;
5542 end Kill_All_Checks;
5544 -----------------
5545 -- Kill_Checks --
5546 -----------------
5548 procedure Kill_Checks (V : Entity_Id) is
5549 begin
5550 if Debug_Flag_CC then
5551 w ("Kill_Checks for entity", Int (V));
5552 end if;
5554 for J in 1 .. Num_Saved_Checks loop
5555 if Saved_Checks (J).Entity = V then
5556 if Debug_Flag_CC then
5557 w (" Checks killed for saved check ", J);
5558 end if;
5560 Saved_Checks (J).Killed := True;
5561 end if;
5562 end loop;
5563 end Kill_Checks;
5565 ------------------------------
5566 -- Length_Checks_Suppressed --
5567 ------------------------------
5569 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5570 begin
5571 if Present (E) and then Checks_May_Be_Suppressed (E) then
5572 return Is_Check_Suppressed (E, Length_Check);
5573 else
5574 return Scope_Suppress (Length_Check);
5575 end if;
5576 end Length_Checks_Suppressed;
5578 --------------------------------
5579 -- Overflow_Checks_Suppressed --
5580 --------------------------------
5582 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5583 begin
5584 if Present (E) and then Checks_May_Be_Suppressed (E) then
5585 return Is_Check_Suppressed (E, Overflow_Check);
5586 else
5587 return Scope_Suppress (Overflow_Check);
5588 end if;
5589 end Overflow_Checks_Suppressed;
5591 -----------------------------
5592 -- Range_Checks_Suppressed --
5593 -----------------------------
5595 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5596 begin
5597 if Present (E) then
5599 -- Note: for now we always suppress range checks on Vax float types,
5600 -- since Gigi does not know how to generate these checks.
5602 if Vax_Float (E) then
5603 return True;
5604 elsif Kill_Range_Checks (E) then
5605 return True;
5606 elsif Checks_May_Be_Suppressed (E) then
5607 return Is_Check_Suppressed (E, Range_Check);
5608 end if;
5609 end if;
5611 return Scope_Suppress (Range_Check);
5612 end Range_Checks_Suppressed;
5614 -----------------------------------------
5615 -- Range_Or_Validity_Checks_Suppressed --
5616 -----------------------------------------
5618 -- Note: the coding would be simpler here if we simply made appropriate
5619 -- calls to Range/Validity_Checks_Suppressed, but that would result in
5620 -- duplicated checks which we prefer to avoid.
5622 function Range_Or_Validity_Checks_Suppressed
5623 (Expr : Node_Id) return Boolean
5625 begin
5626 -- Immediate return if scope checks suppressed for either check
5628 if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5629 return True;
5630 end if;
5632 -- If no expression, that's odd, decide that checks are suppressed,
5633 -- since we don't want anyone trying to do checks in this case, which
5634 -- is most likely the result of some other error.
5636 if No (Expr) then
5637 return True;
5638 end if;
5640 -- Expression is present, so perform suppress checks on type
5642 declare
5643 Typ : constant Entity_Id := Etype (Expr);
5644 begin
5645 if Vax_Float (Typ) then
5646 return True;
5647 elsif Checks_May_Be_Suppressed (Typ)
5648 and then (Is_Check_Suppressed (Typ, Range_Check)
5649 or else
5650 Is_Check_Suppressed (Typ, Validity_Check))
5651 then
5652 return True;
5653 end if;
5654 end;
5656 -- If expression is an entity name, perform checks on this entity
5658 if Is_Entity_Name (Expr) then
5659 declare
5660 Ent : constant Entity_Id := Entity (Expr);
5661 begin
5662 if Checks_May_Be_Suppressed (Ent) then
5663 return Is_Check_Suppressed (Ent, Range_Check)
5664 or else Is_Check_Suppressed (Ent, Validity_Check);
5665 end if;
5666 end;
5667 end if;
5669 -- If we fall through, no checks suppressed
5671 return False;
5672 end Range_Or_Validity_Checks_Suppressed;
5674 -------------------
5675 -- Remove_Checks --
5676 -------------------
5678 procedure Remove_Checks (Expr : Node_Id) is
5679 function Process (N : Node_Id) return Traverse_Result;
5680 -- Process a single node during the traversal
5682 procedure Traverse is new Traverse_Proc (Process);
5683 -- The traversal procedure itself
5685 -------------
5686 -- Process --
5687 -------------
5689 function Process (N : Node_Id) return Traverse_Result is
5690 begin
5691 if Nkind (N) not in N_Subexpr then
5692 return Skip;
5693 end if;
5695 Set_Do_Range_Check (N, False);
5697 case Nkind (N) is
5698 when N_And_Then =>
5699 Traverse (Left_Opnd (N));
5700 return Skip;
5702 when N_Attribute_Reference =>
5703 Set_Do_Overflow_Check (N, False);
5705 when N_Function_Call =>
5706 Set_Do_Tag_Check (N, False);
5708 when N_Op =>
5709 Set_Do_Overflow_Check (N, False);
5711 case Nkind (N) is
5712 when N_Op_Divide =>
5713 Set_Do_Division_Check (N, False);
5715 when N_Op_And =>
5716 Set_Do_Length_Check (N, False);
5718 when N_Op_Mod =>
5719 Set_Do_Division_Check (N, False);
5721 when N_Op_Or =>
5722 Set_Do_Length_Check (N, False);
5724 when N_Op_Rem =>
5725 Set_Do_Division_Check (N, False);
5727 when N_Op_Xor =>
5728 Set_Do_Length_Check (N, False);
5730 when others =>
5731 null;
5732 end case;
5734 when N_Or_Else =>
5735 Traverse (Left_Opnd (N));
5736 return Skip;
5738 when N_Selected_Component =>
5739 Set_Do_Discriminant_Check (N, False);
5741 when N_Type_Conversion =>
5742 Set_Do_Length_Check (N, False);
5743 Set_Do_Tag_Check (N, False);
5744 Set_Do_Overflow_Check (N, False);
5746 when others =>
5747 null;
5748 end case;
5750 return OK;
5751 end Process;
5753 -- Start of processing for Remove_Checks
5755 begin
5756 Traverse (Expr);
5757 end Remove_Checks;
5759 ----------------------------
5760 -- Selected_Length_Checks --
5761 ----------------------------
5763 function Selected_Length_Checks
5764 (Ck_Node : Node_Id;
5765 Target_Typ : Entity_Id;
5766 Source_Typ : Entity_Id;
5767 Warn_Node : Node_Id) return Check_Result
5769 Loc : constant Source_Ptr := Sloc (Ck_Node);
5770 S_Typ : Entity_Id;
5771 T_Typ : Entity_Id;
5772 Expr_Actual : Node_Id;
5773 Exptyp : Entity_Id;
5774 Cond : Node_Id := Empty;
5775 Do_Access : Boolean := False;
5776 Wnode : Node_Id := Warn_Node;
5777 Ret_Result : Check_Result := (Empty, Empty);
5778 Num_Checks : Natural := 0;
5780 procedure Add_Check (N : Node_Id);
5781 -- Adds the action given to Ret_Result if N is non-Empty
5783 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5784 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5785 -- Comments required ???
5787 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5788 -- True for equal literals and for nodes that denote the same constant
5789 -- entity, even if its value is not a static constant. This includes the
5790 -- case of a discriminal reference within an init proc. Removes some
5791 -- obviously superfluous checks.
5793 function Length_E_Cond
5794 (Exptyp : Entity_Id;
5795 Typ : Entity_Id;
5796 Indx : Nat) return Node_Id;
5797 -- Returns expression to compute:
5798 -- Typ'Length /= Exptyp'Length
5800 function Length_N_Cond
5801 (Expr : Node_Id;
5802 Typ : Entity_Id;
5803 Indx : Nat) return Node_Id;
5804 -- Returns expression to compute:
5805 -- Typ'Length /= Expr'Length
5807 ---------------
5808 -- Add_Check --
5809 ---------------
5811 procedure Add_Check (N : Node_Id) is
5812 begin
5813 if Present (N) then
5815 -- For now, ignore attempt to place more than 2 checks ???
5817 if Num_Checks = 2 then
5818 return;
5819 end if;
5821 pragma Assert (Num_Checks <= 1);
5822 Num_Checks := Num_Checks + 1;
5823 Ret_Result (Num_Checks) := N;
5824 end if;
5825 end Add_Check;
5827 ------------------
5828 -- Get_E_Length --
5829 ------------------
5831 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5832 SE : constant Entity_Id := Scope (E);
5833 N : Node_Id;
5834 E1 : Entity_Id := E;
5836 begin
5837 if Ekind (Scope (E)) = E_Record_Type
5838 and then Has_Discriminants (Scope (E))
5839 then
5840 N := Build_Discriminal_Subtype_Of_Component (E);
5842 if Present (N) then
5843 Insert_Action (Ck_Node, N);
5844 E1 := Defining_Identifier (N);
5845 end if;
5846 end if;
5848 if Ekind (E1) = E_String_Literal_Subtype then
5849 return
5850 Make_Integer_Literal (Loc,
5851 Intval => String_Literal_Length (E1));
5853 elsif SE /= Standard_Standard
5854 and then Ekind (Scope (SE)) = E_Protected_Type
5855 and then Has_Discriminants (Scope (SE))
5856 and then Has_Completion (Scope (SE))
5857 and then not Inside_Init_Proc
5858 then
5859 -- If the type whose length is needed is a private component
5860 -- constrained by a discriminant, we must expand the 'Length
5861 -- attribute into an explicit computation, using the discriminal
5862 -- of the current protected operation. This is because the actual
5863 -- type of the prival is constructed after the protected opera-
5864 -- tion has been fully expanded.
5866 declare
5867 Indx_Type : Node_Id;
5868 Lo : Node_Id;
5869 Hi : Node_Id;
5870 Do_Expand : Boolean := False;
5872 begin
5873 Indx_Type := First_Index (E);
5875 for J in 1 .. Indx - 1 loop
5876 Next_Index (Indx_Type);
5877 end loop;
5879 Get_Index_Bounds (Indx_Type, Lo, Hi);
5881 if Nkind (Lo) = N_Identifier
5882 and then Ekind (Entity (Lo)) = E_In_Parameter
5883 then
5884 Lo := Get_Discriminal (E, Lo);
5885 Do_Expand := True;
5886 end if;
5888 if Nkind (Hi) = N_Identifier
5889 and then Ekind (Entity (Hi)) = E_In_Parameter
5890 then
5891 Hi := Get_Discriminal (E, Hi);
5892 Do_Expand := True;
5893 end if;
5895 if Do_Expand then
5896 if not Is_Entity_Name (Lo) then
5897 Lo := Duplicate_Subexpr_No_Checks (Lo);
5898 end if;
5900 if not Is_Entity_Name (Hi) then
5901 Lo := Duplicate_Subexpr_No_Checks (Hi);
5902 end if;
5904 N :=
5905 Make_Op_Add (Loc,
5906 Left_Opnd =>
5907 Make_Op_Subtract (Loc,
5908 Left_Opnd => Hi,
5909 Right_Opnd => Lo),
5911 Right_Opnd => Make_Integer_Literal (Loc, 1));
5912 return N;
5914 else
5915 N :=
5916 Make_Attribute_Reference (Loc,
5917 Attribute_Name => Name_Length,
5918 Prefix =>
5919 New_Occurrence_Of (E1, Loc));
5921 if Indx > 1 then
5922 Set_Expressions (N, New_List (
5923 Make_Integer_Literal (Loc, Indx)));
5924 end if;
5926 return N;
5927 end if;
5928 end;
5930 else
5931 N :=
5932 Make_Attribute_Reference (Loc,
5933 Attribute_Name => Name_Length,
5934 Prefix =>
5935 New_Occurrence_Of (E1, Loc));
5937 if Indx > 1 then
5938 Set_Expressions (N, New_List (
5939 Make_Integer_Literal (Loc, Indx)));
5940 end if;
5942 return N;
5943 end if;
5944 end Get_E_Length;
5946 ------------------
5947 -- Get_N_Length --
5948 ------------------
5950 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5951 begin
5952 return
5953 Make_Attribute_Reference (Loc,
5954 Attribute_Name => Name_Length,
5955 Prefix =>
5956 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5957 Expressions => New_List (
5958 Make_Integer_Literal (Loc, Indx)));
5959 end Get_N_Length;
5961 -------------------
5962 -- Length_E_Cond --
5963 -------------------
5965 function Length_E_Cond
5966 (Exptyp : Entity_Id;
5967 Typ : Entity_Id;
5968 Indx : Nat) return Node_Id
5970 begin
5971 return
5972 Make_Op_Ne (Loc,
5973 Left_Opnd => Get_E_Length (Typ, Indx),
5974 Right_Opnd => Get_E_Length (Exptyp, Indx));
5975 end Length_E_Cond;
5977 -------------------
5978 -- Length_N_Cond --
5979 -------------------
5981 function Length_N_Cond
5982 (Expr : Node_Id;
5983 Typ : Entity_Id;
5984 Indx : Nat) return Node_Id
5986 begin
5987 return
5988 Make_Op_Ne (Loc,
5989 Left_Opnd => Get_E_Length (Typ, Indx),
5990 Right_Opnd => Get_N_Length (Expr, Indx));
5991 end Length_N_Cond;
5993 -----------------
5994 -- Same_Bounds --
5995 -----------------
5997 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5998 begin
5999 return
6000 (Nkind (L) = N_Integer_Literal
6001 and then Nkind (R) = N_Integer_Literal
6002 and then Intval (L) = Intval (R))
6004 or else
6005 (Is_Entity_Name (L)
6006 and then Ekind (Entity (L)) = E_Constant
6007 and then ((Is_Entity_Name (R)
6008 and then Entity (L) = Entity (R))
6009 or else
6010 (Nkind (R) = N_Type_Conversion
6011 and then Is_Entity_Name (Expression (R))
6012 and then Entity (L) = Entity (Expression (R)))))
6014 or else
6015 (Is_Entity_Name (R)
6016 and then Ekind (Entity (R)) = E_Constant
6017 and then Nkind (L) = N_Type_Conversion
6018 and then Is_Entity_Name (Expression (L))
6019 and then Entity (R) = Entity (Expression (L)))
6021 or else
6022 (Is_Entity_Name (L)
6023 and then Is_Entity_Name (R)
6024 and then Entity (L) = Entity (R)
6025 and then Ekind (Entity (L)) = E_In_Parameter
6026 and then Inside_Init_Proc);
6027 end Same_Bounds;
6029 -- Start of processing for Selected_Length_Checks
6031 begin
6032 if not Expander_Active then
6033 return Ret_Result;
6034 end if;
6036 if Target_Typ = Any_Type
6037 or else Target_Typ = Any_Composite
6038 or else Raises_Constraint_Error (Ck_Node)
6039 then
6040 return Ret_Result;
6041 end if;
6043 if No (Wnode) then
6044 Wnode := Ck_Node;
6045 end if;
6047 T_Typ := Target_Typ;
6049 if No (Source_Typ) then
6050 S_Typ := Etype (Ck_Node);
6051 else
6052 S_Typ := Source_Typ;
6053 end if;
6055 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6056 return Ret_Result;
6057 end if;
6059 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6060 S_Typ := Designated_Type (S_Typ);
6061 T_Typ := Designated_Type (T_Typ);
6062 Do_Access := True;
6064 -- A simple optimization for the null case
6066 if Known_Null (Ck_Node) then
6067 return Ret_Result;
6068 end if;
6069 end if;
6071 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6072 if Is_Constrained (T_Typ) then
6074 -- The checking code to be generated will freeze the
6075 -- corresponding array type. However, we must freeze the
6076 -- type now, so that the freeze node does not appear within
6077 -- the generated conditional expression, but ahead of it.
6079 Freeze_Before (Ck_Node, T_Typ);
6081 Expr_Actual := Get_Referenced_Object (Ck_Node);
6082 Exptyp := Get_Actual_Subtype (Ck_Node);
6084 if Is_Access_Type (Exptyp) then
6085 Exptyp := Designated_Type (Exptyp);
6086 end if;
6088 -- String_Literal case. This needs to be handled specially be-
6089 -- cause no index types are available for string literals. The
6090 -- condition is simply:
6092 -- T_Typ'Length = string-literal-length
6094 if Nkind (Expr_Actual) = N_String_Literal
6095 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
6096 then
6097 Cond :=
6098 Make_Op_Ne (Loc,
6099 Left_Opnd => Get_E_Length (T_Typ, 1),
6100 Right_Opnd =>
6101 Make_Integer_Literal (Loc,
6102 Intval =>
6103 String_Literal_Length (Etype (Expr_Actual))));
6105 -- General array case. Here we have a usable actual subtype for
6106 -- the expression, and the condition is built from the two types
6107 -- (Do_Length):
6109 -- T_Typ'Length /= Exptyp'Length or else
6110 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
6111 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
6112 -- ...
6114 elsif Is_Constrained (Exptyp) then
6115 declare
6116 Ndims : constant Nat := Number_Dimensions (T_Typ);
6118 L_Index : Node_Id;
6119 R_Index : Node_Id;
6120 L_Low : Node_Id;
6121 L_High : Node_Id;
6122 R_Low : Node_Id;
6123 R_High : Node_Id;
6124 L_Length : Uint;
6125 R_Length : Uint;
6126 Ref_Node : Node_Id;
6128 begin
6129 -- At the library level, we need to ensure that the type of
6130 -- the object is elaborated before the check itself is
6131 -- emitted. This is only done if the object is in the
6132 -- current compilation unit, otherwise the type is frozen
6133 -- and elaborated in its unit.
6135 if Is_Itype (Exptyp)
6136 and then
6137 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
6138 and then
6139 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
6140 and then In_Open_Scopes (Scope (Exptyp))
6141 then
6142 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
6143 Set_Itype (Ref_Node, Exptyp);
6144 Insert_Action (Ck_Node, Ref_Node);
6145 end if;
6147 L_Index := First_Index (T_Typ);
6148 R_Index := First_Index (Exptyp);
6150 for Indx in 1 .. Ndims loop
6151 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6152 or else
6153 Nkind (R_Index) = N_Raise_Constraint_Error)
6154 then
6155 Get_Index_Bounds (L_Index, L_Low, L_High);
6156 Get_Index_Bounds (R_Index, R_Low, R_High);
6158 -- Deal with compile time length check. Note that we
6159 -- skip this in the access case, because the access
6160 -- value may be null, so we cannot know statically.
6162 if not Do_Access
6163 and then Compile_Time_Known_Value (L_Low)
6164 and then Compile_Time_Known_Value (L_High)
6165 and then Compile_Time_Known_Value (R_Low)
6166 and then Compile_Time_Known_Value (R_High)
6167 then
6168 if Expr_Value (L_High) >= Expr_Value (L_Low) then
6169 L_Length := Expr_Value (L_High) -
6170 Expr_Value (L_Low) + 1;
6171 else
6172 L_Length := UI_From_Int (0);
6173 end if;
6175 if Expr_Value (R_High) >= Expr_Value (R_Low) then
6176 R_Length := Expr_Value (R_High) -
6177 Expr_Value (R_Low) + 1;
6178 else
6179 R_Length := UI_From_Int (0);
6180 end if;
6182 if L_Length > R_Length then
6183 Add_Check
6184 (Compile_Time_Constraint_Error
6185 (Wnode, "too few elements for}?", T_Typ));
6187 elsif L_Length < R_Length then
6188 Add_Check
6189 (Compile_Time_Constraint_Error
6190 (Wnode, "too many elements for}?", T_Typ));
6191 end if;
6193 -- The comparison for an individual index subtype
6194 -- is omitted if the corresponding index subtypes
6195 -- statically match, since the result is known to
6196 -- be true. Note that this test is worth while even
6197 -- though we do static evaluation, because non-static
6198 -- subtypes can statically match.
6200 elsif not
6201 Subtypes_Statically_Match
6202 (Etype (L_Index), Etype (R_Index))
6204 and then not
6205 (Same_Bounds (L_Low, R_Low)
6206 and then Same_Bounds (L_High, R_High))
6207 then
6208 Evolve_Or_Else
6209 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
6210 end if;
6212 Next (L_Index);
6213 Next (R_Index);
6214 end if;
6215 end loop;
6216 end;
6218 -- Handle cases where we do not get a usable actual subtype that
6219 -- is constrained. This happens for example in the function call
6220 -- and explicit dereference cases. In these cases, we have to get
6221 -- the length or range from the expression itself, making sure we
6222 -- do not evaluate it more than once.
6224 -- Here Ck_Node is the original expression, or more properly the
6225 -- result of applying Duplicate_Expr to the original tree, forcing
6226 -- the result to be a name.
6228 else
6229 declare
6230 Ndims : constant Nat := Number_Dimensions (T_Typ);
6232 begin
6233 -- Build the condition for the explicit dereference case
6235 for Indx in 1 .. Ndims loop
6236 Evolve_Or_Else
6237 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
6238 end loop;
6239 end;
6240 end if;
6241 end if;
6242 end if;
6244 -- Construct the test and insert into the tree
6246 if Present (Cond) then
6247 if Do_Access then
6248 Cond := Guard_Access (Cond, Loc, Ck_Node);
6249 end if;
6251 Add_Check
6252 (Make_Raise_Constraint_Error (Loc,
6253 Condition => Cond,
6254 Reason => CE_Length_Check_Failed));
6255 end if;
6257 return Ret_Result;
6258 end Selected_Length_Checks;
6260 ---------------------------
6261 -- Selected_Range_Checks --
6262 ---------------------------
6264 function Selected_Range_Checks
6265 (Ck_Node : Node_Id;
6266 Target_Typ : Entity_Id;
6267 Source_Typ : Entity_Id;
6268 Warn_Node : Node_Id) return Check_Result
6270 Loc : constant Source_Ptr := Sloc (Ck_Node);
6271 S_Typ : Entity_Id;
6272 T_Typ : Entity_Id;
6273 Expr_Actual : Node_Id;
6274 Exptyp : Entity_Id;
6275 Cond : Node_Id := Empty;
6276 Do_Access : Boolean := False;
6277 Wnode : Node_Id := Warn_Node;
6278 Ret_Result : Check_Result := (Empty, Empty);
6279 Num_Checks : Integer := 0;
6281 procedure Add_Check (N : Node_Id);
6282 -- Adds the action given to Ret_Result if N is non-Empty
6284 function Discrete_Range_Cond
6285 (Expr : Node_Id;
6286 Typ : Entity_Id) return Node_Id;
6287 -- Returns expression to compute:
6288 -- Low_Bound (Expr) < Typ'First
6289 -- or else
6290 -- High_Bound (Expr) > Typ'Last
6292 function Discrete_Expr_Cond
6293 (Expr : Node_Id;
6294 Typ : Entity_Id) return Node_Id;
6295 -- Returns expression to compute:
6296 -- Expr < Typ'First
6297 -- or else
6298 -- Expr > Typ'Last
6300 function Get_E_First_Or_Last
6301 (Loc : Source_Ptr;
6302 E : Entity_Id;
6303 Indx : Nat;
6304 Nam : Name_Id) return Node_Id;
6305 -- Returns an attribute reference
6306 -- E'First or E'Last
6307 -- with a source location of Loc.
6309 -- Nam is Name_First or Name_Last, according to which attribute is
6310 -- desired. If Indx is non-zero, it is passed as a literal in the
6311 -- Expressions of the attribute reference (identifying the desired
6312 -- array dimension).
6314 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
6315 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
6316 -- Returns expression to compute:
6317 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
6319 function Range_E_Cond
6320 (Exptyp : Entity_Id;
6321 Typ : Entity_Id;
6322 Indx : Nat)
6323 return Node_Id;
6324 -- Returns expression to compute:
6325 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
6327 function Range_Equal_E_Cond
6328 (Exptyp : Entity_Id;
6329 Typ : Entity_Id;
6330 Indx : Nat) return Node_Id;
6331 -- Returns expression to compute:
6332 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
6334 function Range_N_Cond
6335 (Expr : Node_Id;
6336 Typ : Entity_Id;
6337 Indx : Nat) return Node_Id;
6338 -- Return expression to compute:
6339 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
6341 ---------------
6342 -- Add_Check --
6343 ---------------
6345 procedure Add_Check (N : Node_Id) is
6346 begin
6347 if Present (N) then
6349 -- For now, ignore attempt to place more than 2 checks ???
6351 if Num_Checks = 2 then
6352 return;
6353 end if;
6355 pragma Assert (Num_Checks <= 1);
6356 Num_Checks := Num_Checks + 1;
6357 Ret_Result (Num_Checks) := N;
6358 end if;
6359 end Add_Check;
6361 -------------------------
6362 -- Discrete_Expr_Cond --
6363 -------------------------
6365 function Discrete_Expr_Cond
6366 (Expr : Node_Id;
6367 Typ : Entity_Id) return Node_Id
6369 begin
6370 return
6371 Make_Or_Else (Loc,
6372 Left_Opnd =>
6373 Make_Op_Lt (Loc,
6374 Left_Opnd =>
6375 Convert_To (Base_Type (Typ),
6376 Duplicate_Subexpr_No_Checks (Expr)),
6377 Right_Opnd =>
6378 Convert_To (Base_Type (Typ),
6379 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
6381 Right_Opnd =>
6382 Make_Op_Gt (Loc,
6383 Left_Opnd =>
6384 Convert_To (Base_Type (Typ),
6385 Duplicate_Subexpr_No_Checks (Expr)),
6386 Right_Opnd =>
6387 Convert_To
6388 (Base_Type (Typ),
6389 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
6390 end Discrete_Expr_Cond;
6392 -------------------------
6393 -- Discrete_Range_Cond --
6394 -------------------------
6396 function Discrete_Range_Cond
6397 (Expr : Node_Id;
6398 Typ : Entity_Id) return Node_Id
6400 LB : Node_Id := Low_Bound (Expr);
6401 HB : Node_Id := High_Bound (Expr);
6403 Left_Opnd : Node_Id;
6404 Right_Opnd : Node_Id;
6406 begin
6407 if Nkind (LB) = N_Identifier
6408 and then Ekind (Entity (LB)) = E_Discriminant
6409 then
6410 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6411 end if;
6413 if Nkind (HB) = N_Identifier
6414 and then Ekind (Entity (HB)) = E_Discriminant
6415 then
6416 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6417 end if;
6419 Left_Opnd :=
6420 Make_Op_Lt (Loc,
6421 Left_Opnd =>
6422 Convert_To
6423 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6425 Right_Opnd =>
6426 Convert_To
6427 (Base_Type (Typ),
6428 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
6430 if Base_Type (Typ) = Typ then
6431 return Left_Opnd;
6433 elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6434 and then
6435 Compile_Time_Known_Value (High_Bound (Scalar_Range
6436 (Base_Type (Typ))))
6437 then
6438 if Is_Floating_Point_Type (Typ) then
6439 if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6440 Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6441 then
6442 return Left_Opnd;
6443 end if;
6445 else
6446 if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6447 Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6448 then
6449 return Left_Opnd;
6450 end if;
6451 end if;
6452 end if;
6454 Right_Opnd :=
6455 Make_Op_Gt (Loc,
6456 Left_Opnd =>
6457 Convert_To
6458 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6460 Right_Opnd =>
6461 Convert_To
6462 (Base_Type (Typ),
6463 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
6465 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6466 end Discrete_Range_Cond;
6468 -------------------------
6469 -- Get_E_First_Or_Last --
6470 -------------------------
6472 function Get_E_First_Or_Last
6473 (Loc : Source_Ptr;
6474 E : Entity_Id;
6475 Indx : Nat;
6476 Nam : Name_Id) return Node_Id
6478 Exprs : List_Id;
6479 begin
6480 if Indx > 0 then
6481 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
6482 else
6483 Exprs := No_List;
6484 end if;
6486 return Make_Attribute_Reference (Loc,
6487 Prefix => New_Occurrence_Of (E, Loc),
6488 Attribute_Name => Nam,
6489 Expressions => Exprs);
6490 end Get_E_First_Or_Last;
6492 -----------------
6493 -- Get_N_First --
6494 -----------------
6496 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6497 begin
6498 return
6499 Make_Attribute_Reference (Loc,
6500 Attribute_Name => Name_First,
6501 Prefix =>
6502 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6503 Expressions => New_List (
6504 Make_Integer_Literal (Loc, Indx)));
6505 end Get_N_First;
6507 ----------------
6508 -- Get_N_Last --
6509 ----------------
6511 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6512 begin
6513 return
6514 Make_Attribute_Reference (Loc,
6515 Attribute_Name => Name_Last,
6516 Prefix =>
6517 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6518 Expressions => New_List (
6519 Make_Integer_Literal (Loc, Indx)));
6520 end Get_N_Last;
6522 ------------------
6523 -- Range_E_Cond --
6524 ------------------
6526 function Range_E_Cond
6527 (Exptyp : Entity_Id;
6528 Typ : Entity_Id;
6529 Indx : Nat) return Node_Id
6531 begin
6532 return
6533 Make_Or_Else (Loc,
6534 Left_Opnd =>
6535 Make_Op_Lt (Loc,
6536 Left_Opnd =>
6537 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6538 Right_Opnd =>
6539 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6541 Right_Opnd =>
6542 Make_Op_Gt (Loc,
6543 Left_Opnd =>
6544 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6545 Right_Opnd =>
6546 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6547 end Range_E_Cond;
6549 ------------------------
6550 -- Range_Equal_E_Cond --
6551 ------------------------
6553 function Range_Equal_E_Cond
6554 (Exptyp : Entity_Id;
6555 Typ : Entity_Id;
6556 Indx : Nat) return Node_Id
6558 begin
6559 return
6560 Make_Or_Else (Loc,
6561 Left_Opnd =>
6562 Make_Op_Ne (Loc,
6563 Left_Opnd =>
6564 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6565 Right_Opnd =>
6566 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6568 Right_Opnd =>
6569 Make_Op_Ne (Loc,
6570 Left_Opnd =>
6571 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6572 Right_Opnd =>
6573 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6574 end Range_Equal_E_Cond;
6576 ------------------
6577 -- Range_N_Cond --
6578 ------------------
6580 function Range_N_Cond
6581 (Expr : Node_Id;
6582 Typ : Entity_Id;
6583 Indx : Nat) return Node_Id
6585 begin
6586 return
6587 Make_Or_Else (Loc,
6588 Left_Opnd =>
6589 Make_Op_Lt (Loc,
6590 Left_Opnd =>
6591 Get_N_First (Expr, Indx),
6592 Right_Opnd =>
6593 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6595 Right_Opnd =>
6596 Make_Op_Gt (Loc,
6597 Left_Opnd =>
6598 Get_N_Last (Expr, Indx),
6599 Right_Opnd =>
6600 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6601 end Range_N_Cond;
6603 -- Start of processing for Selected_Range_Checks
6605 begin
6606 if not Expander_Active then
6607 return Ret_Result;
6608 end if;
6610 if Target_Typ = Any_Type
6611 or else Target_Typ = Any_Composite
6612 or else Raises_Constraint_Error (Ck_Node)
6613 then
6614 return Ret_Result;
6615 end if;
6617 if No (Wnode) then
6618 Wnode := Ck_Node;
6619 end if;
6621 T_Typ := Target_Typ;
6623 if No (Source_Typ) then
6624 S_Typ := Etype (Ck_Node);
6625 else
6626 S_Typ := Source_Typ;
6627 end if;
6629 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6630 return Ret_Result;
6631 end if;
6633 -- The order of evaluating T_Typ before S_Typ seems to be critical
6634 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6635 -- in, and since Node can be an N_Range node, it might be invalid.
6636 -- Should there be an assert check somewhere for taking the Etype of
6637 -- an N_Range node ???
6639 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6640 S_Typ := Designated_Type (S_Typ);
6641 T_Typ := Designated_Type (T_Typ);
6642 Do_Access := True;
6644 -- A simple optimization for the null case
6646 if Known_Null (Ck_Node) then
6647 return Ret_Result;
6648 end if;
6649 end if;
6651 -- For an N_Range Node, check for a null range and then if not
6652 -- null generate a range check action.
6654 if Nkind (Ck_Node) = N_Range then
6656 -- There's no point in checking a range against itself
6658 if Ck_Node = Scalar_Range (T_Typ) then
6659 return Ret_Result;
6660 end if;
6662 declare
6663 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
6664 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
6665 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
6666 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
6668 LB : Node_Id := Low_Bound (Ck_Node);
6669 HB : Node_Id := High_Bound (Ck_Node);
6670 Known_LB : Boolean;
6671 Known_HB : Boolean;
6673 Null_Range : Boolean;
6674 Out_Of_Range_L : Boolean;
6675 Out_Of_Range_H : Boolean;
6677 begin
6678 -- Compute what is known at compile time
6680 if Known_T_LB and Known_T_HB then
6681 if Compile_Time_Known_Value (LB) then
6682 Known_LB := True;
6684 -- There's no point in checking that a bound is within its
6685 -- own range so pretend that it is known in this case. First
6686 -- deal with low bound.
6688 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
6689 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
6690 then
6691 LB := T_LB;
6692 Known_LB := True;
6694 else
6695 Known_LB := False;
6696 end if;
6698 -- Likewise for the high bound
6700 if Compile_Time_Known_Value (HB) then
6701 Known_HB := True;
6703 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
6704 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
6705 then
6706 HB := T_HB;
6707 Known_HB := True;
6709 else
6710 Known_HB := False;
6711 end if;
6712 end if;
6714 -- Check for case where everything is static and we can do the
6715 -- check at compile time. This is skipped if we have an access
6716 -- type, since the access value may be null.
6718 -- ??? This code can be improved since you only need to know that
6719 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
6720 -- compile time to emit pertinent messages.
6722 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
6723 and not Do_Access
6724 then
6725 -- Floating-point case
6727 if Is_Floating_Point_Type (S_Typ) then
6728 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6729 Out_Of_Range_L :=
6730 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6731 or else
6732 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6734 Out_Of_Range_H :=
6735 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6736 or else
6737 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6739 -- Fixed or discrete type case
6741 else
6742 Null_Range := Expr_Value (HB) < Expr_Value (LB);
6743 Out_Of_Range_L :=
6744 (Expr_Value (LB) < Expr_Value (T_LB))
6745 or else
6746 (Expr_Value (LB) > Expr_Value (T_HB));
6748 Out_Of_Range_H :=
6749 (Expr_Value (HB) > Expr_Value (T_HB))
6750 or else
6751 (Expr_Value (HB) < Expr_Value (T_LB));
6752 end if;
6754 if not Null_Range then
6755 if Out_Of_Range_L then
6756 if No (Warn_Node) then
6757 Add_Check
6758 (Compile_Time_Constraint_Error
6759 (Low_Bound (Ck_Node),
6760 "static value out of range of}?", T_Typ));
6762 else
6763 Add_Check
6764 (Compile_Time_Constraint_Error
6765 (Wnode,
6766 "static range out of bounds of}?", T_Typ));
6767 end if;
6768 end if;
6770 if Out_Of_Range_H then
6771 if No (Warn_Node) then
6772 Add_Check
6773 (Compile_Time_Constraint_Error
6774 (High_Bound (Ck_Node),
6775 "static value out of range of}?", T_Typ));
6777 else
6778 Add_Check
6779 (Compile_Time_Constraint_Error
6780 (Wnode,
6781 "static range out of bounds of}?", T_Typ));
6782 end if;
6783 end if;
6784 end if;
6786 else
6787 declare
6788 LB : Node_Id := Low_Bound (Ck_Node);
6789 HB : Node_Id := High_Bound (Ck_Node);
6791 begin
6792 -- If either bound is a discriminant and we are within the
6793 -- record declaration, it is a use of the discriminant in a
6794 -- constraint of a component, and nothing can be checked
6795 -- here. The check will be emitted within the init proc.
6796 -- Before then, the discriminal has no real meaning.
6797 -- Similarly, if the entity is a discriminal, there is no
6798 -- check to perform yet.
6800 -- The same holds within a discriminated synchronized type,
6801 -- where the discriminant may constrain a component or an
6802 -- entry family.
6804 if Nkind (LB) = N_Identifier
6805 and then Denotes_Discriminant (LB, True)
6806 then
6807 if Current_Scope = Scope (Entity (LB))
6808 or else Is_Concurrent_Type (Current_Scope)
6809 or else Ekind (Entity (LB)) /= E_Discriminant
6810 then
6811 return Ret_Result;
6812 else
6813 LB :=
6814 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6815 end if;
6816 end if;
6818 if Nkind (HB) = N_Identifier
6819 and then Denotes_Discriminant (HB, True)
6820 then
6821 if Current_Scope = Scope (Entity (HB))
6822 or else Is_Concurrent_Type (Current_Scope)
6823 or else Ekind (Entity (HB)) /= E_Discriminant
6824 then
6825 return Ret_Result;
6826 else
6827 HB :=
6828 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6829 end if;
6830 end if;
6832 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6833 Set_Paren_Count (Cond, 1);
6835 Cond :=
6836 Make_And_Then (Loc,
6837 Left_Opnd =>
6838 Make_Op_Ge (Loc,
6839 Left_Opnd => Duplicate_Subexpr_No_Checks (HB),
6840 Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6841 Right_Opnd => Cond);
6842 end;
6843 end if;
6844 end;
6846 elsif Is_Scalar_Type (S_Typ) then
6848 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
6849 -- except the above simply sets a flag in the node and lets
6850 -- gigi generate the check base on the Etype of the expression.
6851 -- Sometimes, however we want to do a dynamic check against an
6852 -- arbitrary target type, so we do that here.
6854 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6855 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6857 -- For literals, we can tell if the constraint error will be
6858 -- raised at compile time, so we never need a dynamic check, but
6859 -- if the exception will be raised, then post the usual warning,
6860 -- and replace the literal with a raise constraint error
6861 -- expression. As usual, skip this for access types
6863 elsif Compile_Time_Known_Value (Ck_Node)
6864 and then not Do_Access
6865 then
6866 declare
6867 LB : constant Node_Id := Type_Low_Bound (T_Typ);
6868 UB : constant Node_Id := Type_High_Bound (T_Typ);
6870 Out_Of_Range : Boolean;
6871 Static_Bounds : constant Boolean :=
6872 Compile_Time_Known_Value (LB)
6873 and Compile_Time_Known_Value (UB);
6875 begin
6876 -- Following range tests should use Sem_Eval routine ???
6878 if Static_Bounds then
6879 if Is_Floating_Point_Type (S_Typ) then
6880 Out_Of_Range :=
6881 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6882 or else
6883 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6885 -- Fixed or discrete type
6887 else
6888 Out_Of_Range :=
6889 Expr_Value (Ck_Node) < Expr_Value (LB)
6890 or else
6891 Expr_Value (Ck_Node) > Expr_Value (UB);
6892 end if;
6894 -- Bounds of the type are static and the literal is out of
6895 -- range so output a warning message.
6897 if Out_Of_Range then
6898 if No (Warn_Node) then
6899 Add_Check
6900 (Compile_Time_Constraint_Error
6901 (Ck_Node,
6902 "static value out of range of}?", T_Typ));
6904 else
6905 Add_Check
6906 (Compile_Time_Constraint_Error
6907 (Wnode,
6908 "static value out of range of}?", T_Typ));
6909 end if;
6910 end if;
6912 else
6913 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6914 end if;
6915 end;
6917 -- Here for the case of a non-static expression, we need a runtime
6918 -- check unless the source type range is guaranteed to be in the
6919 -- range of the target type.
6921 else
6922 if not In_Subrange_Of (S_Typ, T_Typ) then
6923 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6924 end if;
6925 end if;
6926 end if;
6928 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6929 if Is_Constrained (T_Typ) then
6931 Expr_Actual := Get_Referenced_Object (Ck_Node);
6932 Exptyp := Get_Actual_Subtype (Expr_Actual);
6934 if Is_Access_Type (Exptyp) then
6935 Exptyp := Designated_Type (Exptyp);
6936 end if;
6938 -- String_Literal case. This needs to be handled specially be-
6939 -- cause no index types are available for string literals. The
6940 -- condition is simply:
6942 -- T_Typ'Length = string-literal-length
6944 if Nkind (Expr_Actual) = N_String_Literal then
6945 null;
6947 -- General array case. Here we have a usable actual subtype for
6948 -- the expression, and the condition is built from the two types
6950 -- T_Typ'First < Exptyp'First or else
6951 -- T_Typ'Last > Exptyp'Last or else
6952 -- T_Typ'First(1) < Exptyp'First(1) or else
6953 -- T_Typ'Last(1) > Exptyp'Last(1) or else
6954 -- ...
6956 elsif Is_Constrained (Exptyp) then
6957 declare
6958 Ndims : constant Nat := Number_Dimensions (T_Typ);
6960 L_Index : Node_Id;
6961 R_Index : Node_Id;
6963 begin
6964 L_Index := First_Index (T_Typ);
6965 R_Index := First_Index (Exptyp);
6967 for Indx in 1 .. Ndims loop
6968 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6969 or else
6970 Nkind (R_Index) = N_Raise_Constraint_Error)
6971 then
6972 -- Deal with compile time length check. Note that we
6973 -- skip this in the access case, because the access
6974 -- value may be null, so we cannot know statically.
6976 if not
6977 Subtypes_Statically_Match
6978 (Etype (L_Index), Etype (R_Index))
6979 then
6980 -- If the target type is constrained then we
6981 -- have to check for exact equality of bounds
6982 -- (required for qualified expressions).
6984 if Is_Constrained (T_Typ) then
6985 Evolve_Or_Else
6986 (Cond,
6987 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6988 else
6989 Evolve_Or_Else
6990 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6991 end if;
6992 end if;
6994 Next (L_Index);
6995 Next (R_Index);
6996 end if;
6997 end loop;
6998 end;
7000 -- Handle cases where we do not get a usable actual subtype that
7001 -- is constrained. This happens for example in the function call
7002 -- and explicit dereference cases. In these cases, we have to get
7003 -- the length or range from the expression itself, making sure we
7004 -- do not evaluate it more than once.
7006 -- Here Ck_Node is the original expression, or more properly the
7007 -- result of applying Duplicate_Expr to the original tree,
7008 -- forcing the result to be a name.
7010 else
7011 declare
7012 Ndims : constant Nat := Number_Dimensions (T_Typ);
7014 begin
7015 -- Build the condition for the explicit dereference case
7017 for Indx in 1 .. Ndims loop
7018 Evolve_Or_Else
7019 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
7020 end loop;
7021 end;
7022 end if;
7024 else
7025 -- For a conversion to an unconstrained array type, generate an
7026 -- Action to check that the bounds of the source value are within
7027 -- the constraints imposed by the target type (RM 4.6(38)). No
7028 -- check is needed for a conversion to an access to unconstrained
7029 -- array type, as 4.6(24.15/2) requires the designated subtypes
7030 -- of the two access types to statically match.
7032 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
7033 and then not Do_Access
7034 then
7035 declare
7036 Opnd_Index : Node_Id;
7037 Targ_Index : Node_Id;
7038 Opnd_Range : Node_Id;
7040 begin
7041 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
7042 Targ_Index := First_Index (T_Typ);
7043 while Present (Opnd_Index) loop
7045 -- If the index is a range, use its bounds. If it is an
7046 -- entity (as will be the case if it is a named subtype
7047 -- or an itype created for a slice) retrieve its range.
7049 if Is_Entity_Name (Opnd_Index)
7050 and then Is_Type (Entity (Opnd_Index))
7051 then
7052 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
7053 else
7054 Opnd_Range := Opnd_Index;
7055 end if;
7057 if Nkind (Opnd_Range) = N_Range then
7058 if Is_In_Range
7059 (Low_Bound (Opnd_Range), Etype (Targ_Index),
7060 Assume_Valid => True)
7061 and then
7062 Is_In_Range
7063 (High_Bound (Opnd_Range), Etype (Targ_Index),
7064 Assume_Valid => True)
7065 then
7066 null;
7068 -- If null range, no check needed
7070 elsif
7071 Compile_Time_Known_Value (High_Bound (Opnd_Range))
7072 and then
7073 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
7074 and then
7075 Expr_Value (High_Bound (Opnd_Range)) <
7076 Expr_Value (Low_Bound (Opnd_Range))
7077 then
7078 null;
7080 elsif Is_Out_Of_Range
7081 (Low_Bound (Opnd_Range), Etype (Targ_Index),
7082 Assume_Valid => True)
7083 or else
7084 Is_Out_Of_Range
7085 (High_Bound (Opnd_Range), Etype (Targ_Index),
7086 Assume_Valid => True)
7087 then
7088 Add_Check
7089 (Compile_Time_Constraint_Error
7090 (Wnode, "value out of range of}?", T_Typ));
7092 else
7093 Evolve_Or_Else
7094 (Cond,
7095 Discrete_Range_Cond
7096 (Opnd_Range, Etype (Targ_Index)));
7097 end if;
7098 end if;
7100 Next_Index (Opnd_Index);
7101 Next_Index (Targ_Index);
7102 end loop;
7103 end;
7104 end if;
7105 end if;
7106 end if;
7108 -- Construct the test and insert into the tree
7110 if Present (Cond) then
7111 if Do_Access then
7112 Cond := Guard_Access (Cond, Loc, Ck_Node);
7113 end if;
7115 Add_Check
7116 (Make_Raise_Constraint_Error (Loc,
7117 Condition => Cond,
7118 Reason => CE_Range_Check_Failed));
7119 end if;
7121 return Ret_Result;
7122 end Selected_Range_Checks;
7124 -------------------------------
7125 -- Storage_Checks_Suppressed --
7126 -------------------------------
7128 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
7129 begin
7130 if Present (E) and then Checks_May_Be_Suppressed (E) then
7131 return Is_Check_Suppressed (E, Storage_Check);
7132 else
7133 return Scope_Suppress (Storage_Check);
7134 end if;
7135 end Storage_Checks_Suppressed;
7137 ---------------------------
7138 -- Tag_Checks_Suppressed --
7139 ---------------------------
7141 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
7142 begin
7143 if Present (E) then
7144 if Kill_Tag_Checks (E) then
7145 return True;
7146 elsif Checks_May_Be_Suppressed (E) then
7147 return Is_Check_Suppressed (E, Tag_Check);
7148 end if;
7149 end if;
7151 return Scope_Suppress (Tag_Check);
7152 end Tag_Checks_Suppressed;
7154 --------------------------
7155 -- Validity_Check_Range --
7156 --------------------------
7158 procedure Validity_Check_Range (N : Node_Id) is
7159 begin
7160 if Validity_Checks_On and Validity_Check_Operands then
7161 if Nkind (N) = N_Range then
7162 Ensure_Valid (Low_Bound (N));
7163 Ensure_Valid (High_Bound (N));
7164 end if;
7165 end if;
7166 end Validity_Check_Range;
7168 --------------------------------
7169 -- Validity_Checks_Suppressed --
7170 --------------------------------
7172 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
7173 begin
7174 if Present (E) and then Checks_May_Be_Suppressed (E) then
7175 return Is_Check_Suppressed (E, Validity_Check);
7176 else
7177 return Scope_Suppress (Validity_Check);
7178 end if;
7179 end Validity_Checks_Suppressed;
7181 end Checks;