]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/ada/checks.adb
[Ada] Variable-sized node types
[thirdparty/gcc.git] / gcc / ada / checks.adb
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-2021, 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 ------------------------------------------------------------------------------
25
26 with Atree; use Atree;
27 with Casing; use Casing;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Einfo.Entities; use Einfo.Entities;
31 with Einfo.Utils; use Einfo.Utils;
32 with Elists; use Elists;
33 with Eval_Fat; use Eval_Fat;
34 with Exp_Ch11; use Exp_Ch11;
35 with Exp_Ch4; use Exp_Ch4;
36 with Exp_Pakd; use Exp_Pakd;
37 with Exp_Util; use Exp_Util;
38 with Expander; use Expander;
39 with Freeze; use Freeze;
40 with Lib; use Lib;
41 with Nlists; use Nlists;
42 with Nmake; use Nmake;
43 with Opt; use Opt;
44 with Output; use Output;
45 with Restrict; use Restrict;
46 with Rident; use Rident;
47 with Rtsfind; use Rtsfind;
48 with Sem; use Sem;
49 with Sem_Aux; use Sem_Aux;
50 with Sem_Ch3; use Sem_Ch3;
51 with Sem_Ch8; use Sem_Ch8;
52 with Sem_Disp; use Sem_Disp;
53 with Sem_Eval; use Sem_Eval;
54 with Sem_Mech; use Sem_Mech;
55 with Sem_Res; use Sem_Res;
56 with Sem_Util; use Sem_Util;
57 with Sem_Warn; use Sem_Warn;
58 with Sinfo; use Sinfo;
59 with Sinfo.Nodes; use Sinfo.Nodes;
60 with Sinfo.Utils; use Sinfo.Utils;
61 with Sinput; use Sinput;
62 with Snames; use Snames;
63 with Sprint; use Sprint;
64 with Stand; use Stand;
65 with Stringt; use Stringt;
66 with Targparm; use Targparm;
67 with Tbuild; use Tbuild;
68 with Ttypes; use Ttypes;
69 with Validsw; use Validsw;
70
71 package body Checks is
72
73 -- General note: many of these routines are concerned with generating
74 -- checking code to make sure that constraint error is raised at runtime.
75 -- Clearly this code is only needed if the expander is active, since
76 -- otherwise we will not be generating code or going into the runtime
77 -- execution anyway.
78
79 -- We therefore disconnect most of these checks if the expander is
80 -- inactive. This has the additional benefit that we do not need to
81 -- worry about the tree being messed up by previous errors (since errors
82 -- turn off expansion anyway).
83
84 -- There are a few exceptions to the above rule. For instance routines
85 -- such as Apply_Scalar_Range_Check that do not insert any code can be
86 -- safely called even when the Expander is inactive (but Errors_Detected
87 -- is 0). The benefit of executing this code when expansion is off, is
88 -- the ability to emit constraint error warning for static expressions
89 -- even when we are not generating code.
90
91 -- The above is modified in gnatprove mode to ensure that proper check
92 -- flags are always placed, even if expansion is off.
93
94 -------------------------------------
95 -- Suppression of Redundant Checks --
96 -------------------------------------
97
98 -- This unit implements a limited circuit for removal of redundant
99 -- checks. The processing is based on a tracing of simple sequential
100 -- flow. For any sequence of statements, we save expressions that are
101 -- marked to be checked, and then if the same expression appears later
102 -- with the same check, then under certain circumstances, the second
103 -- check can be suppressed.
104
105 -- Basically, we can suppress the check if we know for certain that
106 -- the previous expression has been elaborated (together with its
107 -- check), and we know that the exception frame is the same, and that
108 -- nothing has happened to change the result of the exception.
109
110 -- Let us examine each of these three conditions in turn to describe
111 -- how we ensure that this condition is met.
112
113 -- First, we need to know for certain that the previous expression has
114 -- been executed. This is done principally by the mechanism of calling
115 -- Conditional_Statements_Begin at the start of any statement sequence
116 -- and Conditional_Statements_End at the end. The End call causes all
117 -- checks remembered since the Begin call to be discarded. This does
118 -- miss a few cases, notably the case of a nested BEGIN-END block with
119 -- no exception handlers. But the important thing is to be conservative.
120 -- The other protection is that all checks are discarded if a label
121 -- is encountered, since then the assumption of sequential execution
122 -- is violated, and we don't know enough about the flow.
123
124 -- Second, we need to know that the exception frame is the same. We
125 -- do this by killing all remembered checks when we enter a new frame.
126 -- Again, that's over-conservative, but generally the cases we can help
127 -- with are pretty local anyway (like the body of a loop for example).
128
129 -- Third, we must be sure to forget any checks which are no longer valid.
130 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
131 -- used to note any changes to local variables. We only attempt to deal
132 -- with checks involving local variables, so we do not need to worry
133 -- about global variables. Second, a call to any non-global procedure
134 -- causes us to abandon all stored checks, since such a all may affect
135 -- the values of any local variables.
136
137 -- The following define the data structures used to deal with remembering
138 -- checks so that redundant checks can be eliminated as described above.
139
140 -- Right now, the only expressions that we deal with are of the form of
141 -- simple local objects (either declared locally, or IN parameters) or
142 -- such objects plus/minus a compile time known constant. We can do
143 -- more later on if it seems worthwhile, but this catches many simple
144 -- cases in practice.
145
146 -- The following record type reflects a single saved check. An entry
147 -- is made in the stack of saved checks if and only if the expression
148 -- has been elaborated with the indicated checks.
149
150 type Saved_Check is record
151 Killed : Boolean;
152 -- Set True if entry is killed by Kill_Checks
153
154 Entity : Entity_Id;
155 -- The entity involved in the expression that is checked
156
157 Offset : Uint;
158 -- A compile time value indicating the result of adding or
159 -- subtracting a compile time value. This value is to be
160 -- added to the value of the Entity. A value of zero is
161 -- used for the case of a simple entity reference.
162
163 Check_Type : Character;
164 -- This is set to 'R' for a range check (in which case Target_Type
165 -- is set to the target type for the range check) or to 'O' for an
166 -- overflow check (in which case Target_Type is set to Empty).
167
168 Target_Type : Entity_Id;
169 -- Used only if Do_Range_Check is set. Records the target type for
170 -- the check. We need this, because a check is a duplicate only if
171 -- it has the same target type (or more accurately one with a
172 -- range that is smaller or equal to the stored target type of a
173 -- saved check).
174 end record;
175
176 -- The following table keeps track of saved checks. Rather than use an
177 -- extensible table, we just use a table of fixed size, and we discard
178 -- any saved checks that do not fit. That's very unlikely to happen and
179 -- this is only an optimization in any case.
180
181 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
182 -- Array of saved checks
183
184 Num_Saved_Checks : Nat := 0;
185 -- Number of saved checks
186
187 -- The following stack keeps track of statement ranges. It is treated
188 -- as a stack. When Conditional_Statements_Begin is called, an entry
189 -- is pushed onto this stack containing the value of Num_Saved_Checks
190 -- at the time of the call. Then when Conditional_Statements_End is
191 -- called, this value is popped off and used to reset Num_Saved_Checks.
192
193 -- Note: again, this is a fixed length stack with a size that should
194 -- always be fine. If the value of the stack pointer goes above the
195 -- limit, then we just forget all saved checks.
196
197 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
198 Saved_Checks_TOS : Nat := 0;
199
200 -----------------------
201 -- Local Subprograms --
202 -----------------------
203
204 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id);
205 -- Used to apply arithmetic overflow checks for all cases except operators
206 -- on signed arithmetic types in MINIMIZED/ELIMINATED case (for which we
207 -- call Apply_Arithmetic_Overflow_Minimized_Eliminated below). N can be a
208 -- signed integer arithmetic operator (but not an if or case expression).
209 -- It is also called for types other than signed integers.
210
211 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id);
212 -- Used to apply arithmetic overflow checks for the case where the overflow
213 -- checking mode is MINIMIZED or ELIMINATED and we have a signed integer
214 -- arithmetic op (which includes the case of if and case expressions). Note
215 -- that Do_Overflow_Check may or may not be set for node Op. In these modes
216 -- we have work to do even if overflow checking is suppressed.
217
218 procedure Apply_Division_Check
219 (N : Node_Id;
220 Rlo : Uint;
221 Rhi : Uint;
222 ROK : Boolean);
223 -- N is an N_Op_Div, N_Op_Rem, or N_Op_Mod node. This routine applies
224 -- division checks as required if the Do_Division_Check flag is set.
225 -- Rlo and Rhi give the possible range of the right operand, these values
226 -- can be referenced and trusted only if ROK is set True.
227
228 procedure Apply_Float_Conversion_Check
229 (Expr : Node_Id;
230 Target_Typ : Entity_Id);
231 -- The checks on a conversion from a floating-point type to an integer
232 -- type are delicate. They have to be performed before conversion, they
233 -- have to raise an exception when the operand is a NaN, and rounding must
234 -- be taken into account to determine the safe bounds of the operand.
235
236 procedure Apply_Selected_Length_Checks
237 (Expr : Node_Id;
238 Target_Typ : Entity_Id;
239 Source_Typ : Entity_Id;
240 Do_Static : Boolean);
241 -- This is the subprogram that does all the work for Apply_Length_Check
242 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
243 -- described for the above routines. The Do_Static flag indicates that
244 -- only a static check is to be done.
245
246 procedure Compute_Range_For_Arithmetic_Op
247 (Op : Node_Kind;
248 Lo_Left : Uint;
249 Hi_Left : Uint;
250 Lo_Right : Uint;
251 Hi_Right : Uint;
252 OK : out Boolean;
253 Lo : out Uint;
254 Hi : out Uint);
255 -- Given an integer arithmetical operation Op and the range of values of
256 -- its operand(s), try to compute a conservative estimate of the possible
257 -- range of values for the result of the operation. Thus if OK is True on
258 -- return, the result is known to lie in the range Lo .. Hi (inclusive).
259 -- If OK is false, both Lo and Hi are set to No_Uint.
260
261 type Check_Type is new Check_Id range Access_Check .. Division_Check;
262 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
263 -- This function is used to see if an access or division by zero check is
264 -- needed. The check is to be applied to a single variable appearing in the
265 -- source, and N is the node for the reference. If N is not of this form,
266 -- True is returned with no further processing. If N is of the right form,
267 -- then further processing determines if the given Check is needed.
268 --
269 -- The particular circuit is to see if we have the case of a check that is
270 -- not needed because it appears in the right operand of a short circuited
271 -- conditional where the left operand guards the check. For example:
272 --
273 -- if Var = 0 or else Q / Var > 12 then
274 -- ...
275 -- end if;
276 --
277 -- In this example, the division check is not required. At the same time
278 -- we can issue warnings for suspicious use of non-short-circuited forms,
279 -- such as:
280 --
281 -- if Var = 0 or Q / Var > 12 then
282 -- ...
283 -- end if;
284
285 procedure Find_Check
286 (Expr : Node_Id;
287 Check_Type : Character;
288 Target_Type : Entity_Id;
289 Entry_OK : out Boolean;
290 Check_Num : out Nat;
291 Ent : out Entity_Id;
292 Ofs : out Uint);
293 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
294 -- to see if a check is of the form for optimization, and if so, to see
295 -- if it has already been performed. Expr is the expression to check,
296 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
297 -- Target_Type is the target type for a range check, and Empty for an
298 -- overflow check. If the entry is not of the form for optimization,
299 -- then Entry_OK is set to False, and the remaining out parameters
300 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
301 -- entity and offset from the expression. Check_Num is the number of
302 -- a matching saved entry in Saved_Checks, or zero if no such entry
303 -- is located.
304
305 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
306 -- If a discriminal is used in constraining a prival, Return reference
307 -- to the discriminal of the protected body (which renames the parameter
308 -- of the enclosing protected operation). This clumsy transformation is
309 -- needed because privals are created too late and their actual subtypes
310 -- are not available when analysing the bodies of the protected operations.
311 -- This function is called whenever the bound is an entity and the scope
312 -- indicates a protected operation. If the bound is an in-parameter of
313 -- a protected operation that is not a prival, the function returns the
314 -- bound itself.
315 -- To be cleaned up???
316
317 function Guard_Access
318 (Cond : Node_Id;
319 Loc : Source_Ptr;
320 Expr : Node_Id) return Node_Id;
321 -- In the access type case, guard the test with a test to ensure
322 -- that the access value is non-null, since the checks do not
323 -- not apply to null access values.
324
325 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
326 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
327 -- Constraint_Error node.
328
329 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean;
330 -- Returns True if node N is for an arithmetic operation with signed
331 -- integer operands. This includes unary and binary operators, and also
332 -- if and case expression nodes where the dependent expressions are of
333 -- a signed integer type. These are the kinds of nodes for which special
334 -- handling applies in MINIMIZED or ELIMINATED overflow checking mode.
335
336 function Range_Or_Validity_Checks_Suppressed
337 (Expr : Node_Id) return Boolean;
338 -- Returns True if either range or validity checks or both are suppressed
339 -- for the type of the given expression, or, if the expression is the name
340 -- of an entity, if these checks are suppressed for the entity.
341
342 function Selected_Length_Checks
343 (Expr : Node_Id;
344 Target_Typ : Entity_Id;
345 Source_Typ : Entity_Id;
346 Warn_Node : Node_Id) return Check_Result;
347 -- Like Apply_Selected_Length_Checks, except it doesn't modify
348 -- anything, just returns a list of nodes as described in the spec of
349 -- this package for the Range_Check function.
350 -- ??? In fact it does construct the test and insert it into the tree,
351 -- and insert actions in various ways (calling Insert_Action directly
352 -- in particular) so we do not call it in GNATprove mode, contrary to
353 -- Selected_Range_Checks.
354
355 function Selected_Range_Checks
356 (Expr : Node_Id;
357 Target_Typ : Entity_Id;
358 Source_Typ : Entity_Id;
359 Warn_Node : Node_Id) return Check_Result;
360 -- Like Apply_Range_Check, except it does not modify anything, just
361 -- returns a list of nodes as described in the spec of this package
362 -- for the Range_Check function.
363
364 ------------------------------
365 -- Access_Checks_Suppressed --
366 ------------------------------
367
368 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
369 begin
370 if Present (E) and then Checks_May_Be_Suppressed (E) then
371 return Is_Check_Suppressed (E, Access_Check);
372 else
373 return Scope_Suppress.Suppress (Access_Check);
374 end if;
375 end Access_Checks_Suppressed;
376
377 -------------------------------------
378 -- Accessibility_Checks_Suppressed --
379 -------------------------------------
380
381 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
382 begin
383 if Present (E) and then Checks_May_Be_Suppressed (E) then
384 return Is_Check_Suppressed (E, Accessibility_Check);
385 else
386 return Scope_Suppress.Suppress (Accessibility_Check);
387 end if;
388 end Accessibility_Checks_Suppressed;
389
390 -----------------------------
391 -- Activate_Division_Check --
392 -----------------------------
393
394 procedure Activate_Division_Check (N : Node_Id) is
395 begin
396 Set_Do_Division_Check (N, True);
397 Possible_Local_Raise (N, Standard_Constraint_Error);
398 end Activate_Division_Check;
399
400 -----------------------------
401 -- Activate_Overflow_Check --
402 -----------------------------
403
404 procedure Activate_Overflow_Check (N : Node_Id) is
405 Typ : constant Entity_Id := Etype (N);
406
407 begin
408 -- Floating-point case. If Etype is not set (this can happen when we
409 -- activate a check on a node that has not yet been analyzed), then
410 -- we assume we do not have a floating-point type (as per our spec).
411
412 if Present (Typ) and then Is_Floating_Point_Type (Typ) then
413
414 -- Ignore call if we have no automatic overflow checks on the target
415 -- and Check_Float_Overflow mode is not set. These are the cases in
416 -- which we expect to generate infinities and NaN's with no check.
417
418 if not (Machine_Overflows_On_Target or Check_Float_Overflow) then
419 return;
420
421 -- Ignore for unary operations ("+", "-", abs) since these can never
422 -- result in overflow for floating-point cases.
423
424 elsif Nkind (N) in N_Unary_Op then
425 return;
426
427 -- Otherwise we will set the flag
428
429 else
430 null;
431 end if;
432
433 -- Discrete case
434
435 else
436 -- Nothing to do for Rem/Mod/Plus (overflow not possible, the check
437 -- for zero-divide is a divide check, not an overflow check).
438
439 if Nkind (N) in N_Op_Rem | N_Op_Mod | N_Op_Plus then
440 return;
441 end if;
442 end if;
443
444 -- Fall through for cases where we do set the flag
445
446 Set_Do_Overflow_Check (N);
447 Possible_Local_Raise (N, Standard_Constraint_Error);
448 end Activate_Overflow_Check;
449
450 --------------------------
451 -- Activate_Range_Check --
452 --------------------------
453
454 procedure Activate_Range_Check (N : Node_Id) is
455 begin
456 Set_Do_Range_Check (N);
457 Possible_Local_Raise (N, Standard_Constraint_Error);
458 end Activate_Range_Check;
459
460 ---------------------------------
461 -- Alignment_Checks_Suppressed --
462 ---------------------------------
463
464 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
465 begin
466 if Present (E) and then Checks_May_Be_Suppressed (E) then
467 return Is_Check_Suppressed (E, Alignment_Check);
468 else
469 return Scope_Suppress.Suppress (Alignment_Check);
470 end if;
471 end Alignment_Checks_Suppressed;
472
473 ----------------------------------
474 -- Allocation_Checks_Suppressed --
475 ----------------------------------
476
477 -- Note: at the current time there are no calls to this function, because
478 -- the relevant check is in the run-time, so it is not a check that the
479 -- compiler can suppress anyway, but we still have to recognize the check
480 -- name Allocation_Check since it is part of the standard.
481
482 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean is
483 begin
484 if Present (E) and then Checks_May_Be_Suppressed (E) then
485 return Is_Check_Suppressed (E, Allocation_Check);
486 else
487 return Scope_Suppress.Suppress (Allocation_Check);
488 end if;
489 end Allocation_Checks_Suppressed;
490
491 -------------------------
492 -- Append_Range_Checks --
493 -------------------------
494
495 procedure Append_Range_Checks
496 (Checks : Check_Result;
497 Stmts : List_Id;
498 Suppress_Typ : Entity_Id;
499 Static_Sloc : Source_Ptr)
500 is
501 Checks_On : constant Boolean :=
502 not Index_Checks_Suppressed (Suppress_Typ)
503 or else
504 not Range_Checks_Suppressed (Suppress_Typ);
505
506 begin
507 -- For now we just return if Checks_On is false, however this could be
508 -- enhanced to check for an always True value in the condition and to
509 -- generate a compilation warning.
510
511 if not Checks_On then
512 return;
513 end if;
514
515 for J in 1 .. 2 loop
516 exit when No (Checks (J));
517
518 if Nkind (Checks (J)) = N_Raise_Constraint_Error
519 and then Present (Condition (Checks (J)))
520 then
521 Append_To (Stmts, Checks (J));
522 else
523 Append_To
524 (Stmts,
525 Make_Raise_Constraint_Error (Static_Sloc,
526 Reason => CE_Range_Check_Failed));
527 end if;
528 end loop;
529 end Append_Range_Checks;
530
531 ------------------------
532 -- Apply_Access_Check --
533 ------------------------
534
535 procedure Apply_Access_Check (N : Node_Id) is
536 P : constant Node_Id := Prefix (N);
537
538 begin
539 -- We do not need checks if we are not generating code (i.e. the
540 -- expander is not active). This is not just an optimization, there
541 -- are cases (e.g. with pragma Debug) where generating the checks
542 -- can cause real trouble.
543
544 if not Expander_Active then
545 return;
546 end if;
547
548 -- No check if short circuiting makes check unnecessary
549
550 if not Check_Needed (P, Access_Check) then
551 return;
552 end if;
553
554 -- No check if accessing the Offset_To_Top component of a dispatch
555 -- table. They are safe by construction.
556
557 if Tagged_Type_Expansion
558 and then Present (Etype (P))
559 and then Is_RTE (Etype (P), RE_Offset_To_Top_Ptr)
560 then
561 return;
562 end if;
563
564 -- Otherwise go ahead and install the check
565
566 Install_Null_Excluding_Check (P);
567 end Apply_Access_Check;
568
569 -------------------------------
570 -- Apply_Accessibility_Check --
571 -------------------------------
572
573 procedure Apply_Accessibility_Check
574 (N : Node_Id;
575 Typ : Entity_Id;
576 Insert_Node : Node_Id)
577 is
578 Loc : constant Source_Ptr := Sloc (N);
579
580 Check_Cond : Node_Id;
581 Param_Ent : Entity_Id := Param_Entity (N);
582 Param_Level : Node_Id;
583 Type_Level : Node_Id;
584
585 begin
586 if Ada_Version >= Ada_2012
587 and then not Present (Param_Ent)
588 and then Is_Entity_Name (N)
589 and then Ekind (Entity (N)) in E_Constant | E_Variable
590 and then Present (Effective_Extra_Accessibility (Entity (N)))
591 then
592 Param_Ent := Entity (N);
593 while Present (Renamed_Object (Param_Ent)) loop
594 -- Renamed_Object must return an Entity_Name here
595 -- because of preceding "Present (E_E_A (...))" test.
596
597 Param_Ent := Entity (Renamed_Object (Param_Ent));
598 end loop;
599 end if;
600
601 if Inside_A_Generic then
602 return;
603
604 -- Only apply the run-time check if the access parameter has an
605 -- associated extra access level parameter and when accessibility checks
606 -- are enabled.
607
608 elsif Present (Param_Ent)
609 and then Present (Get_Dynamic_Accessibility (Param_Ent))
610 and then not Accessibility_Checks_Suppressed (Param_Ent)
611 and then not Accessibility_Checks_Suppressed (Typ)
612 then
613 -- Obtain the parameter's accessibility level
614
615 Param_Level :=
616 New_Occurrence_Of (Get_Dynamic_Accessibility (Param_Ent), Loc);
617
618 -- Use the dynamic accessibility parameter for the function's result
619 -- when one has been created instead of statically referring to the
620 -- deepest type level so as to appropriatly handle the rules for
621 -- RM 3.10.2 (10.1/3).
622
623 if Ekind (Scope (Param_Ent)) = E_Function
624 and then In_Return_Value (N)
625 and then Ekind (Typ) = E_Anonymous_Access_Type
626 then
627 -- Associate the level of the result type to the extra result
628 -- accessibility parameter belonging to the current function.
629
630 if Present (Extra_Accessibility_Of_Result (Scope (Param_Ent))) then
631 Type_Level :=
632 New_Occurrence_Of
633 (Extra_Accessibility_Of_Result (Scope (Param_Ent)), Loc);
634
635 -- In Ada 2005 and earlier modes, a result extra accessibility
636 -- parameter is not generated and no dynamic check is performed.
637
638 else
639 return;
640 end if;
641
642 -- Otherwise get the type's accessibility level normally
643
644 else
645 Type_Level :=
646 Make_Integer_Literal (Loc, Deepest_Type_Access_Level (Typ));
647 end if;
648
649 -- Raise Program_Error if the accessibility level of the access
650 -- parameter is deeper than the level of the target access type.
651
652 Check_Cond :=
653 Make_Op_Gt (Loc,
654 Left_Opnd => Param_Level,
655 Right_Opnd => Type_Level);
656
657 Insert_Action (Insert_Node,
658 Make_Raise_Program_Error (Loc,
659 Condition => Check_Cond,
660 Reason => PE_Accessibility_Check_Failed));
661
662 Analyze_And_Resolve (N);
663
664 -- If constant folding has happened on the condition for the
665 -- generated error, then warn about it being unconditional.
666
667 if Nkind (Check_Cond) = N_Identifier
668 and then Entity (Check_Cond) = Standard_True
669 then
670 Error_Msg_Warn := SPARK_Mode /= On;
671 Error_Msg_N ("accessibility check fails<<", N);
672 Error_Msg_N ("\Program_Error [<<", N);
673 end if;
674 end if;
675 end Apply_Accessibility_Check;
676
677 --------------------------------
678 -- Apply_Address_Clause_Check --
679 --------------------------------
680
681 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
682 pragma Assert (Nkind (N) = N_Freeze_Entity);
683
684 AC : constant Node_Id := Address_Clause (E);
685 Loc : constant Source_Ptr := Sloc (AC);
686 Typ : constant Entity_Id := Etype (E);
687
688 Expr : Node_Id;
689 -- Address expression (not necessarily the same as Aexp, for example
690 -- when Aexp is a reference to a constant, in which case Expr gets
691 -- reset to reference the value expression of the constant).
692
693 begin
694 -- See if alignment check needed. Note that we never need a check if the
695 -- maximum alignment is one, since the check will always succeed.
696
697 -- Note: we do not check for checks suppressed here, since that check
698 -- was done in Sem_Ch13 when the address clause was processed. We are
699 -- only called if checks were not suppressed. The reason for this is
700 -- that we have to delay the call to Apply_Alignment_Check till freeze
701 -- time (so that all types etc are elaborated), but we have to check
702 -- the status of check suppressing at the point of the address clause.
703
704 if No (AC)
705 or else not Check_Address_Alignment (AC)
706 or else Maximum_Alignment = 1
707 then
708 return;
709 end if;
710
711 -- Obtain expression from address clause
712
713 Expr := Address_Value (Expression (AC));
714
715 -- See if we know that Expr has an acceptable value at compile time. If
716 -- it hasn't or we don't know, we defer issuing the warning until the
717 -- end of the compilation to take into account back end annotations.
718
719 if Compile_Time_Known_Value (Expr)
720 and then (Known_Alignment (E) or else Known_Alignment (Typ))
721 then
722 declare
723 AL : Uint := Alignment (Typ);
724
725 begin
726 -- The object alignment might be more restrictive than the type
727 -- alignment.
728
729 if Known_Alignment (E) then
730 AL := Alignment (E);
731 end if;
732
733 if Expr_Value (Expr) mod AL = 0 then
734 return;
735 end if;
736 end;
737
738 -- If the expression has the form X'Address, then we can find out if the
739 -- object X has an alignment that is compatible with the object E. If it
740 -- hasn't or we don't know, we defer issuing the warning until the end
741 -- of the compilation to take into account back end annotations.
742
743 elsif Nkind (Expr) = N_Attribute_Reference
744 and then Attribute_Name (Expr) = Name_Address
745 and then
746 Has_Compatible_Alignment (E, Prefix (Expr), False) = Known_Compatible
747 then
748 return;
749 end if;
750
751 -- Here we do not know if the value is acceptable. Strictly we don't
752 -- have to do anything, since if the alignment is bad, we have an
753 -- erroneous program. However we are allowed to check for erroneous
754 -- conditions and we decide to do this by default if the check is not
755 -- suppressed.
756
757 -- However, don't do the check if elaboration code is unwanted
758
759 if Restriction_Active (No_Elaboration_Code) then
760 return;
761
762 -- Generate a check to raise PE if alignment may be inappropriate
763
764 else
765 -- If the original expression is a nonstatic constant, use the name
766 -- of the constant itself rather than duplicating its initialization
767 -- expression, which was extracted above.
768
769 -- Note: Expr is empty if the address-clause is applied to in-mode
770 -- actuals (allowed by 13.1(22)).
771
772 if not Present (Expr)
773 or else
774 (Is_Entity_Name (Expression (AC))
775 and then Ekind (Entity (Expression (AC))) = E_Constant
776 and then Nkind (Parent (Entity (Expression (AC)))) =
777 N_Object_Declaration)
778 then
779 Expr := New_Copy_Tree (Expression (AC));
780 else
781 Remove_Side_Effects (Expr);
782 end if;
783
784 if No (Actions (N)) then
785 Set_Actions (N, New_List);
786 end if;
787
788 Prepend_To (Actions (N),
789 Make_Raise_Program_Error (Loc,
790 Condition =>
791 Make_Op_Ne (Loc,
792 Left_Opnd =>
793 Make_Op_Mod (Loc,
794 Left_Opnd =>
795 Unchecked_Convert_To
796 (RTE (RE_Integer_Address), Expr),
797 Right_Opnd =>
798 Make_Attribute_Reference (Loc,
799 Prefix => New_Occurrence_Of (E, Loc),
800 Attribute_Name => Name_Alignment)),
801 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
802 Reason => PE_Misaligned_Address_Value));
803
804 Warning_Msg := No_Error_Msg;
805 Analyze (First (Actions (N)), Suppress => All_Checks);
806
807 -- If the above raise action generated a warning message (for example
808 -- from Warn_On_Non_Local_Exception mode with the active restriction
809 -- No_Exception_Propagation).
810
811 if Warning_Msg /= No_Error_Msg then
812
813 -- If the expression has a known at compile time value, then
814 -- once we know the alignment of the type, we can check if the
815 -- exception will be raised or not, and if not, we don't need
816 -- the warning so we will kill the warning later on.
817
818 if Compile_Time_Known_Value (Expr) then
819 Alignment_Warnings.Append
820 ((E => E,
821 A => Expr_Value (Expr),
822 P => Empty,
823 W => Warning_Msg));
824
825 -- Likewise if the expression is of the form X'Address
826
827 elsif Nkind (Expr) = N_Attribute_Reference
828 and then Attribute_Name (Expr) = Name_Address
829 then
830 Alignment_Warnings.Append
831 ((E => E,
832 A => No_Uint,
833 P => Prefix (Expr),
834 W => Warning_Msg));
835
836 -- Add explanation of the warning generated by the check
837
838 else
839 Error_Msg_N
840 ("\address value may be incompatible with alignment of "
841 & "object?X?", AC);
842 end if;
843 end if;
844
845 return;
846 end if;
847
848 exception
849
850 -- If we have some missing run time component in configurable run time
851 -- mode then just skip the check (it is not required in any case).
852
853 when RE_Not_Available =>
854 return;
855 end Apply_Address_Clause_Check;
856
857 -------------------------------------
858 -- Apply_Arithmetic_Overflow_Check --
859 -------------------------------------
860
861 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
862 begin
863 -- Use old routine in almost all cases (the only case we are treating
864 -- specially is the case of a signed integer arithmetic op with the
865 -- overflow checking mode set to MINIMIZED or ELIMINATED).
866
867 if Overflow_Check_Mode = Strict
868 or else not Is_Signed_Integer_Arithmetic_Op (N)
869 then
870 Apply_Arithmetic_Overflow_Strict (N);
871
872 -- Otherwise use the new routine for the case of a signed integer
873 -- arithmetic op, with Do_Overflow_Check set to True, and the checking
874 -- mode is MINIMIZED or ELIMINATED.
875
876 else
877 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
878 end if;
879 end Apply_Arithmetic_Overflow_Check;
880
881 --------------------------------------
882 -- Apply_Arithmetic_Overflow_Strict --
883 --------------------------------------
884
885 -- This routine is called only if the type is an integer type and an
886 -- arithmetic overflow check may be needed for op (add, subtract, or
887 -- multiply). This check is performed if Backend_Overflow_Checks_On_Target
888 -- is not enabled and Do_Overflow_Check is set. In this case we expand the
889 -- operation into a more complex sequence of tests that ensures that
890 -- overflow is properly caught.
891
892 -- This is used in CHECKED modes. It is identical to the code for this
893 -- cases before the big overflow earthquake, thus ensuring that in this
894 -- modes we have compatible behavior (and reliability) to what was there
895 -- before. It is also called for types other than signed integers, and if
896 -- the Do_Overflow_Check flag is off.
897
898 -- Note: we also call this routine if we decide in the MINIMIZED case
899 -- to give up and just generate an overflow check without any fuss.
900
901 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id) is
902 Loc : constant Source_Ptr := Sloc (N);
903 Typ : constant Entity_Id := Etype (N);
904 Rtyp : constant Entity_Id := Root_Type (Typ);
905
906 begin
907 -- Nothing to do if Do_Overflow_Check not set or overflow checks
908 -- suppressed.
909
910 if not Do_Overflow_Check (N) then
911 return;
912 end if;
913
914 -- An interesting special case. If the arithmetic operation appears as
915 -- the operand of a type conversion:
916
917 -- type1 (x op y)
918
919 -- and all the following conditions apply:
920
921 -- arithmetic operation is for a signed integer type
922 -- target type type1 is a static integer subtype
923 -- range of x and y are both included in the range of type1
924 -- range of x op y is included in the range of type1
925 -- size of type1 is at least twice the result size of op
926
927 -- then we don't do an overflow check in any case. Instead, we transform
928 -- the operation so that we end up with:
929
930 -- type1 (type1 (x) op type1 (y))
931
932 -- This avoids intermediate overflow before the conversion. It is
933 -- explicitly permitted by RM 3.5.4(24):
934
935 -- For the execution of a predefined operation of a signed integer
936 -- type, the implementation need not raise Constraint_Error if the
937 -- result is outside the base range of the type, so long as the
938 -- correct result is produced.
939
940 -- It's hard to imagine that any programmer counts on the exception
941 -- being raised in this case, and in any case it's wrong coding to
942 -- have this expectation, given the RM permission. Furthermore, other
943 -- Ada compilers do allow such out of range results.
944
945 -- Note that we do this transformation even if overflow checking is
946 -- off, since this is precisely about giving the "right" result and
947 -- avoiding the need for an overflow check.
948
949 -- Note: this circuit is partially redundant with respect to the similar
950 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
951 -- with cases that do not come through here. We still need the following
952 -- processing even with the Exp_Ch4 code in place, since we want to be
953 -- sure not to generate the arithmetic overflow check in these cases
954 -- (Exp_Ch4 would have a hard time removing them once generated).
955
956 if Is_Signed_Integer_Type (Typ)
957 and then Nkind (Parent (N)) = N_Type_Conversion
958 then
959 Conversion_Optimization : declare
960 Target_Type : constant Entity_Id :=
961 Base_Type (Entity (Subtype_Mark (Parent (N))));
962
963 Llo, Lhi : Uint;
964 Rlo, Rhi : Uint;
965 LOK, ROK : Boolean;
966
967 Vlo : Uint;
968 Vhi : Uint;
969 VOK : Boolean;
970
971 Tlo : Uint;
972 Thi : Uint;
973
974 begin
975 if Is_Integer_Type (Target_Type)
976 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
977 then
978 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
979 Thi := Expr_Value (Type_High_Bound (Target_Type));
980
981 Determine_Range
982 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
983 Determine_Range
984 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
985
986 if (LOK and ROK)
987 and then Tlo <= Llo and then Lhi <= Thi
988 and then Tlo <= Rlo and then Rhi <= Thi
989 then
990 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
991
992 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
993 Rewrite (Left_Opnd (N),
994 Make_Type_Conversion (Loc,
995 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
996 Expression => Relocate_Node (Left_Opnd (N))));
997
998 Rewrite (Right_Opnd (N),
999 Make_Type_Conversion (Loc,
1000 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
1001 Expression => Relocate_Node (Right_Opnd (N))));
1002
1003 -- Rewrite the conversion operand so that the original
1004 -- node is retained, in order to avoid the warning for
1005 -- redundant conversions in Resolve_Type_Conversion.
1006
1007 Rewrite (N, Relocate_Node (N));
1008
1009 Set_Etype (N, Target_Type);
1010
1011 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
1012 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
1013
1014 -- Given that the target type is twice the size of the
1015 -- source type, overflow is now impossible, so we can
1016 -- safely kill the overflow check and return.
1017
1018 Set_Do_Overflow_Check (N, False);
1019 return;
1020 end if;
1021 end if;
1022 end if;
1023 end Conversion_Optimization;
1024 end if;
1025
1026 -- Now see if an overflow check is required
1027
1028 declare
1029 Dsiz : constant Uint := 2 * Esize (Rtyp);
1030 Opnod : Node_Id;
1031 Ctyp : Entity_Id;
1032 Opnd : Node_Id;
1033 Cent : RE_Id;
1034
1035 begin
1036 -- Skip check if back end does overflow checks, or the overflow flag
1037 -- is not set anyway, or we are not doing code expansion, or the
1038 -- parent node is a type conversion whose operand is an arithmetic
1039 -- operation on signed integers on which the expander can promote
1040 -- later the operands to type Integer (see Expand_N_Type_Conversion).
1041
1042 if Backend_Overflow_Checks_On_Target
1043 or else not Do_Overflow_Check (N)
1044 or else not Expander_Active
1045 or else (Present (Parent (N))
1046 and then Nkind (Parent (N)) = N_Type_Conversion
1047 and then Integer_Promotion_Possible (Parent (N)))
1048 then
1049 return;
1050 end if;
1051
1052 -- Otherwise, generate the full general code for front end overflow
1053 -- detection, which works by doing arithmetic in a larger type:
1054
1055 -- x op y
1056
1057 -- is expanded into
1058
1059 -- Typ (Checktyp (x) op Checktyp (y));
1060
1061 -- where Typ is the type of the original expression, and Checktyp is
1062 -- an integer type of sufficient length to hold the largest possible
1063 -- result.
1064
1065 -- If the size of the check type exceeds the maximum integer size,
1066 -- we use a different approach, expanding to:
1067
1068 -- typ (xxx_With_Ovflo_Check (Integer_NN (x), Integer_NN (y)))
1069
1070 -- where xxx is Add, Multiply or Subtract as appropriate
1071
1072 -- Find check type if one exists
1073
1074 if Dsiz <= System_Max_Integer_Size then
1075 Ctyp := Integer_Type_For (Dsiz, Uns => False);
1076
1077 -- No check type exists, use runtime call
1078
1079 else
1080 if System_Max_Integer_Size = 64 then
1081 Ctyp := RTE (RE_Integer_64);
1082 else
1083 Ctyp := RTE (RE_Integer_128);
1084 end if;
1085
1086 if Nkind (N) = N_Op_Add then
1087 if System_Max_Integer_Size = 64 then
1088 Cent := RE_Add_With_Ovflo_Check64;
1089 else
1090 Cent := RE_Add_With_Ovflo_Check128;
1091 end if;
1092
1093 elsif Nkind (N) = N_Op_Subtract then
1094 if System_Max_Integer_Size = 64 then
1095 Cent := RE_Subtract_With_Ovflo_Check64;
1096 else
1097 Cent := RE_Subtract_With_Ovflo_Check128;
1098 end if;
1099
1100 else pragma Assert (Nkind (N) = N_Op_Multiply);
1101 if System_Max_Integer_Size = 64 then
1102 Cent := RE_Multiply_With_Ovflo_Check64;
1103 else
1104 Cent := RE_Multiply_With_Ovflo_Check128;
1105 end if;
1106 end if;
1107
1108 Rewrite (N,
1109 OK_Convert_To (Typ,
1110 Make_Function_Call (Loc,
1111 Name => New_Occurrence_Of (RTE (Cent), Loc),
1112 Parameter_Associations => New_List (
1113 OK_Convert_To (Ctyp, Left_Opnd (N)),
1114 OK_Convert_To (Ctyp, Right_Opnd (N))))));
1115
1116 Analyze_And_Resolve (N, Typ);
1117 return;
1118 end if;
1119
1120 -- If we fall through, we have the case where we do the arithmetic
1121 -- in the next higher type and get the check by conversion. In these
1122 -- cases Ctyp is set to the type to be used as the check type.
1123
1124 Opnod := Relocate_Node (N);
1125
1126 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
1127
1128 Analyze (Opnd);
1129 Set_Etype (Opnd, Ctyp);
1130 Set_Analyzed (Opnd, True);
1131 Set_Left_Opnd (Opnod, Opnd);
1132
1133 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
1134
1135 Analyze (Opnd);
1136 Set_Etype (Opnd, Ctyp);
1137 Set_Analyzed (Opnd, True);
1138 Set_Right_Opnd (Opnod, Opnd);
1139
1140 -- The type of the operation changes to the base type of the check
1141 -- type, and we reset the overflow check indication, since clearly no
1142 -- overflow is possible now that we are using a double length type.
1143 -- We also set the Analyzed flag to avoid a recursive attempt to
1144 -- expand the node.
1145
1146 Set_Etype (Opnod, Base_Type (Ctyp));
1147 Set_Do_Overflow_Check (Opnod, False);
1148 Set_Analyzed (Opnod, True);
1149
1150 -- Now build the outer conversion
1151
1152 Opnd := OK_Convert_To (Typ, Opnod);
1153 Analyze (Opnd);
1154 Set_Etype (Opnd, Typ);
1155
1156 -- In the discrete type case, we directly generate the range check
1157 -- for the outer operand. This range check will implement the
1158 -- required overflow check.
1159
1160 if Is_Discrete_Type (Typ) then
1161 Rewrite (N, Opnd);
1162 Generate_Range_Check
1163 (Expression (N), Typ, CE_Overflow_Check_Failed);
1164
1165 -- For other types, we enable overflow checking on the conversion,
1166 -- after setting the node as analyzed to prevent recursive attempts
1167 -- to expand the conversion node.
1168
1169 else
1170 Set_Analyzed (Opnd, True);
1171 Enable_Overflow_Check (Opnd);
1172 Rewrite (N, Opnd);
1173 end if;
1174
1175 exception
1176 when RE_Not_Available =>
1177 return;
1178 end;
1179 end Apply_Arithmetic_Overflow_Strict;
1180
1181 ----------------------------------------------------
1182 -- Apply_Arithmetic_Overflow_Minimized_Eliminated --
1183 ----------------------------------------------------
1184
1185 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id) is
1186 pragma Assert (Is_Signed_Integer_Arithmetic_Op (Op));
1187
1188 Loc : constant Source_Ptr := Sloc (Op);
1189 P : constant Node_Id := Parent (Op);
1190
1191 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
1192 -- Operands and results are of this type when we convert
1193
1194 Result_Type : constant Entity_Id := Etype (Op);
1195 -- Original result type
1196
1197 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1198 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
1199
1200 Lo, Hi : Uint;
1201 -- Ranges of values for result
1202
1203 begin
1204 -- Nothing to do if our parent is one of the following:
1205
1206 -- Another signed integer arithmetic op
1207 -- A membership operation
1208 -- A comparison operation
1209
1210 -- In all these cases, we will process at the higher level (and then
1211 -- this node will be processed during the downwards recursion that
1212 -- is part of the processing in Minimize_Eliminate_Overflows).
1213
1214 if Is_Signed_Integer_Arithmetic_Op (P)
1215 or else Nkind (P) in N_Membership_Test
1216 or else Nkind (P) in N_Op_Compare
1217
1218 -- This is also true for an alternative in a case expression
1219
1220 or else Nkind (P) = N_Case_Expression_Alternative
1221
1222 -- This is also true for a range operand in a membership test
1223
1224 or else (Nkind (P) = N_Range
1225 and then Nkind (Parent (P)) in N_Membership_Test)
1226 then
1227 -- If_Expressions and Case_Expressions are treated as arithmetic
1228 -- ops, but if they appear in an assignment or similar contexts
1229 -- there is no overflow check that starts from that parent node,
1230 -- so apply check now.
1231
1232 if Nkind (P) in N_If_Expression | N_Case_Expression
1233 and then not Is_Signed_Integer_Arithmetic_Op (Parent (P))
1234 then
1235 null;
1236 else
1237 return;
1238 end if;
1239 end if;
1240
1241 -- Otherwise, we have a top level arithmetic operation node, and this
1242 -- is where we commence the special processing for MINIMIZED/ELIMINATED
1243 -- modes. This is the case where we tell the machinery not to move into
1244 -- Bignum mode at this top level (of course the top level operation
1245 -- will still be in Bignum mode if either of its operands are of type
1246 -- Bignum).
1247
1248 Minimize_Eliminate_Overflows (Op, Lo, Hi, Top_Level => True);
1249
1250 -- That call may but does not necessarily change the result type of Op.
1251 -- It is the job of this routine to undo such changes, so that at the
1252 -- top level, we have the proper type. This "undoing" is a point at
1253 -- which a final overflow check may be applied.
1254
1255 -- If the result type was not fiddled we are all set. We go to base
1256 -- types here because things may have been rewritten to generate the
1257 -- base type of the operand types.
1258
1259 if Base_Type (Etype (Op)) = Base_Type (Result_Type) then
1260 return;
1261
1262 -- Bignum case
1263
1264 elsif Is_RTE (Etype (Op), RE_Bignum) then
1265
1266 -- We need a sequence that looks like:
1267
1268 -- Rnn : Result_Type;
1269
1270 -- declare
1271 -- M : Mark_Id := SS_Mark;
1272 -- begin
1273 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
1274 -- SS_Release (M);
1275 -- end;
1276
1277 -- This block is inserted (using Insert_Actions), and then the node
1278 -- is replaced with a reference to Rnn.
1279
1280 -- If our parent is a conversion node then there is no point in
1281 -- generating a conversion to Result_Type. Instead, we let the parent
1282 -- handle this. Note that this special case is not just about
1283 -- optimization. Consider
1284
1285 -- A,B,C : Integer;
1286 -- ...
1287 -- X := Long_Long_Integer'Base (A * (B ** C));
1288
1289 -- Now the product may fit in Long_Long_Integer but not in Integer.
1290 -- In MINIMIZED/ELIMINATED mode, we don't want to introduce an
1291 -- overflow exception for this intermediate value.
1292
1293 declare
1294 Blk : constant Node_Id := Make_Bignum_Block (Loc);
1295 Rnn : constant Entity_Id := Make_Temporary (Loc, 'R', Op);
1296 RHS : Node_Id;
1297
1298 Rtype : Entity_Id;
1299
1300 begin
1301 RHS := Convert_From_Bignum (Op);
1302
1303 if Nkind (P) /= N_Type_Conversion then
1304 Convert_To_And_Rewrite (Result_Type, RHS);
1305 Rtype := Result_Type;
1306
1307 -- Interesting question, do we need a check on that conversion
1308 -- operation. Answer, not if we know the result is in range.
1309 -- At the moment we are not taking advantage of this. To be
1310 -- looked at later ???
1311
1312 else
1313 Rtype := LLIB;
1314 end if;
1315
1316 Insert_Before
1317 (First (Statements (Handled_Statement_Sequence (Blk))),
1318 Make_Assignment_Statement (Loc,
1319 Name => New_Occurrence_Of (Rnn, Loc),
1320 Expression => RHS));
1321
1322 Insert_Actions (Op, New_List (
1323 Make_Object_Declaration (Loc,
1324 Defining_Identifier => Rnn,
1325 Object_Definition => New_Occurrence_Of (Rtype, Loc)),
1326 Blk));
1327
1328 Rewrite (Op, New_Occurrence_Of (Rnn, Loc));
1329 Analyze_And_Resolve (Op);
1330 end;
1331
1332 -- Here we know the result is Long_Long_Integer'Base, or that it has
1333 -- been rewritten because the parent operation is a conversion. See
1334 -- Apply_Arithmetic_Overflow_Strict.Conversion_Optimization.
1335
1336 else
1337 pragma Assert
1338 (Etype (Op) = LLIB or else Nkind (Parent (Op)) = N_Type_Conversion);
1339
1340 -- All we need to do here is to convert the result to the proper
1341 -- result type. As explained above for the Bignum case, we can
1342 -- omit this if our parent is a type conversion.
1343
1344 if Nkind (P) /= N_Type_Conversion then
1345 Convert_To_And_Rewrite (Result_Type, Op);
1346 end if;
1347
1348 Analyze_And_Resolve (Op);
1349 end if;
1350 end Apply_Arithmetic_Overflow_Minimized_Eliminated;
1351
1352 ----------------------------
1353 -- Apply_Constraint_Check --
1354 ----------------------------
1355
1356 procedure Apply_Constraint_Check
1357 (N : Node_Id;
1358 Typ : Entity_Id;
1359 No_Sliding : Boolean := False)
1360 is
1361 Desig_Typ : Entity_Id;
1362
1363 begin
1364 -- No checks inside a generic (check the instantiations)
1365
1366 if Inside_A_Generic then
1367 return;
1368 end if;
1369
1370 -- Apply required constraint checks
1371
1372 if Is_Scalar_Type (Typ) then
1373 Apply_Scalar_Range_Check (N, Typ);
1374
1375 elsif Is_Array_Type (Typ) then
1376
1377 -- A useful optimization: an aggregate with only an others clause
1378 -- always has the right bounds.
1379
1380 if Nkind (N) = N_Aggregate
1381 and then No (Expressions (N))
1382 and then Nkind
1383 (First (Choices (First (Component_Associations (N)))))
1384 = N_Others_Choice
1385 then
1386 return;
1387 end if;
1388
1389 if Is_Constrained (Typ) then
1390 Apply_Length_Check (N, Typ);
1391
1392 if No_Sliding then
1393 Apply_Range_Check (N, Typ);
1394 end if;
1395 else
1396 Apply_Range_Check (N, Typ);
1397 end if;
1398
1399 elsif (Is_Record_Type (Typ) or else Is_Private_Type (Typ))
1400 and then Has_Discriminants (Base_Type (Typ))
1401 and then Is_Constrained (Typ)
1402 then
1403 Apply_Discriminant_Check (N, Typ);
1404
1405 elsif Is_Access_Type (Typ) then
1406
1407 Desig_Typ := Designated_Type (Typ);
1408
1409 -- No checks necessary if expression statically null
1410
1411 if Known_Null (N) then
1412 if Can_Never_Be_Null (Typ) then
1413 Install_Null_Excluding_Check (N);
1414 end if;
1415
1416 -- No sliding possible on access to arrays
1417
1418 elsif Is_Array_Type (Desig_Typ) then
1419 if Is_Constrained (Desig_Typ) then
1420 Apply_Length_Check (N, Typ);
1421 end if;
1422
1423 Apply_Range_Check (N, Typ);
1424
1425 -- Do not install a discriminant check for a constrained subtype
1426 -- created for an unconstrained nominal type because the subtype
1427 -- has the correct constraints by construction.
1428
1429 elsif Has_Discriminants (Base_Type (Desig_Typ))
1430 and then Is_Constrained (Desig_Typ)
1431 and then not Is_Constr_Subt_For_U_Nominal (Desig_Typ)
1432 then
1433 Apply_Discriminant_Check (N, Typ);
1434 end if;
1435
1436 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1437 -- this check if the constraint node is illegal, as shown by having
1438 -- an error posted. This additional guard prevents cascaded errors
1439 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1440
1441 if Can_Never_Be_Null (Typ)
1442 and then not Can_Never_Be_Null (Etype (N))
1443 and then not Error_Posted (N)
1444 then
1445 Install_Null_Excluding_Check (N);
1446 end if;
1447 end if;
1448 end Apply_Constraint_Check;
1449
1450 ------------------------------
1451 -- Apply_Discriminant_Check --
1452 ------------------------------
1453
1454 procedure Apply_Discriminant_Check
1455 (N : Node_Id;
1456 Typ : Entity_Id;
1457 Lhs : Node_Id := Empty)
1458 is
1459 Loc : constant Source_Ptr := Sloc (N);
1460 Do_Access : constant Boolean := Is_Access_Type (Typ);
1461 S_Typ : Entity_Id := Etype (N);
1462 Cond : Node_Id;
1463 T_Typ : Entity_Id;
1464
1465 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1466 -- A heap object with an indefinite subtype is constrained by its
1467 -- initial value, and assigning to it requires a constraint_check.
1468 -- The target may be an explicit dereference, or a renaming of one.
1469
1470 function Is_Aliased_Unconstrained_Component return Boolean;
1471 -- It is possible for an aliased component to have a nominal
1472 -- unconstrained subtype (through instantiation). If this is a
1473 -- discriminated component assigned in the expansion of an aggregate
1474 -- in an initialization, the check must be suppressed. This unusual
1475 -- situation requires a predicate of its own.
1476
1477 ----------------------------------
1478 -- Denotes_Explicit_Dereference --
1479 ----------------------------------
1480
1481 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1482 begin
1483 return
1484 Nkind (Obj) = N_Explicit_Dereference
1485 or else
1486 (Is_Entity_Name (Obj)
1487 and then Present (Renamed_Object (Entity (Obj)))
1488 and then Nkind (Renamed_Object (Entity (Obj))) =
1489 N_Explicit_Dereference);
1490 end Denotes_Explicit_Dereference;
1491
1492 ----------------------------------------
1493 -- Is_Aliased_Unconstrained_Component --
1494 ----------------------------------------
1495
1496 function Is_Aliased_Unconstrained_Component return Boolean is
1497 Comp : Entity_Id;
1498 Pref : Node_Id;
1499
1500 begin
1501 if Nkind (Lhs) /= N_Selected_Component then
1502 return False;
1503 else
1504 Comp := Entity (Selector_Name (Lhs));
1505 Pref := Prefix (Lhs);
1506 end if;
1507
1508 if Ekind (Comp) /= E_Component
1509 or else not Is_Aliased (Comp)
1510 then
1511 return False;
1512 end if;
1513
1514 return not Comes_From_Source (Pref)
1515 and then In_Instance
1516 and then not Is_Constrained (Etype (Comp));
1517 end Is_Aliased_Unconstrained_Component;
1518
1519 -- Start of processing for Apply_Discriminant_Check
1520
1521 begin
1522 if Do_Access then
1523 T_Typ := Designated_Type (Typ);
1524 else
1525 T_Typ := Typ;
1526 end if;
1527
1528 -- If the expression is a function call that returns a limited object
1529 -- it cannot be copied. It is not clear how to perform the proper
1530 -- discriminant check in this case because the discriminant value must
1531 -- be retrieved from the constructed object itself.
1532
1533 if Nkind (N) = N_Function_Call
1534 and then Is_Limited_Type (Typ)
1535 and then Is_Entity_Name (Name (N))
1536 and then Returns_By_Ref (Entity (Name (N)))
1537 then
1538 return;
1539 end if;
1540
1541 -- Only apply checks when generating code and discriminant checks are
1542 -- not suppressed. In GNATprove mode, we do not apply the checks, but we
1543 -- still analyze the expression to possibly issue errors on SPARK code
1544 -- when a run-time error can be detected at compile time.
1545
1546 if not GNATprove_Mode then
1547 if not Expander_Active
1548 or else Discriminant_Checks_Suppressed (T_Typ)
1549 then
1550 return;
1551 end if;
1552 end if;
1553
1554 -- No discriminant checks necessary for an access when expression is
1555 -- statically Null. This is not only an optimization, it is fundamental
1556 -- because otherwise discriminant checks may be generated in init procs
1557 -- for types containing an access to a not-yet-frozen record, causing a
1558 -- deadly forward reference.
1559
1560 -- Also, if the expression is of an access type whose designated type is
1561 -- incomplete, then the access value must be null and we suppress the
1562 -- check.
1563
1564 if Known_Null (N) then
1565 return;
1566
1567 elsif Is_Access_Type (S_Typ) then
1568 S_Typ := Designated_Type (S_Typ);
1569
1570 if Ekind (S_Typ) = E_Incomplete_Type then
1571 return;
1572 end if;
1573 end if;
1574
1575 -- If an assignment target is present, then we need to generate the
1576 -- actual subtype if the target is a parameter or aliased object with
1577 -- an unconstrained nominal subtype.
1578
1579 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1580 -- subtype to the parameter and dereference cases, since other aliased
1581 -- objects are unconstrained (unless the nominal subtype is explicitly
1582 -- constrained).
1583
1584 if Present (Lhs)
1585 and then (Present (Param_Entity (Lhs))
1586 or else (Ada_Version < Ada_2005
1587 and then not Is_Constrained (T_Typ)
1588 and then Is_Aliased_View (Lhs)
1589 and then not Is_Aliased_Unconstrained_Component)
1590 or else (Ada_Version >= Ada_2005
1591 and then not Is_Constrained (T_Typ)
1592 and then Denotes_Explicit_Dereference (Lhs)
1593 and then Nkind (Original_Node (Lhs)) /=
1594 N_Function_Call))
1595 then
1596 T_Typ := Get_Actual_Subtype (Lhs);
1597 end if;
1598
1599 -- Nothing to do if the type is unconstrained (this is the case where
1600 -- the actual subtype in the RM sense of N is unconstrained and no check
1601 -- is required).
1602
1603 if not Is_Constrained (T_Typ) then
1604 return;
1605
1606 -- Ada 2005: nothing to do if the type is one for which there is a
1607 -- partial view that is constrained.
1608
1609 elsif Ada_Version >= Ada_2005
1610 and then Object_Type_Has_Constrained_Partial_View
1611 (Typ => Base_Type (T_Typ),
1612 Scop => Current_Scope)
1613 then
1614 return;
1615 end if;
1616
1617 -- Nothing to do if the type is an Unchecked_Union
1618
1619 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1620 return;
1621 end if;
1622
1623 -- Suppress checks if the subtypes are the same. The check must be
1624 -- preserved in an assignment to a formal, because the constraint is
1625 -- given by the actual.
1626
1627 if Nkind (Original_Node (N)) /= N_Allocator
1628 and then (No (Lhs)
1629 or else not Is_Entity_Name (Lhs)
1630 or else No (Param_Entity (Lhs)))
1631 then
1632 if (Etype (N) = Typ
1633 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1634 and then not Is_Aliased_View (Lhs)
1635 then
1636 return;
1637 end if;
1638
1639 -- We can also eliminate checks on allocators with a subtype mark that
1640 -- coincides with the context type. The context type may be a subtype
1641 -- without a constraint (common case, a generic actual).
1642
1643 elsif Nkind (Original_Node (N)) = N_Allocator
1644 and then Is_Entity_Name (Expression (Original_Node (N)))
1645 then
1646 declare
1647 Alloc_Typ : constant Entity_Id :=
1648 Entity (Expression (Original_Node (N)));
1649
1650 begin
1651 if Alloc_Typ = T_Typ
1652 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1653 and then Is_Entity_Name (
1654 Subtype_Indication (Parent (T_Typ)))
1655 and then Alloc_Typ = Base_Type (T_Typ))
1656
1657 then
1658 return;
1659 end if;
1660 end;
1661 end if;
1662
1663 -- See if we have a case where the types are both constrained, and all
1664 -- the constraints are constants. In this case, we can do the check
1665 -- successfully at compile time.
1666
1667 -- We skip this check for the case where the node is rewritten as
1668 -- an allocator, because it already carries the context subtype,
1669 -- and extracting the discriminants from the aggregate is messy.
1670
1671 if Is_Constrained (S_Typ)
1672 and then Nkind (Original_Node (N)) /= N_Allocator
1673 then
1674 declare
1675 DconT : Elmt_Id;
1676 Discr : Entity_Id;
1677 DconS : Elmt_Id;
1678 ItemS : Node_Id;
1679 ItemT : Node_Id;
1680
1681 begin
1682 -- S_Typ may not have discriminants in the case where it is a
1683 -- private type completed by a default discriminated type. In that
1684 -- case, we need to get the constraints from the underlying type.
1685 -- If the underlying type is unconstrained (i.e. has no default
1686 -- discriminants) no check is needed.
1687
1688 if Has_Discriminants (S_Typ) then
1689 Discr := First_Discriminant (S_Typ);
1690 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1691
1692 else
1693 Discr := First_Discriminant (Underlying_Type (S_Typ));
1694 DconS :=
1695 First_Elmt
1696 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1697
1698 if No (DconS) then
1699 return;
1700 end if;
1701
1702 -- A further optimization: if T_Typ is derived from S_Typ
1703 -- without imposing a constraint, no check is needed.
1704
1705 if Nkind (Original_Node (Parent (T_Typ))) =
1706 N_Full_Type_Declaration
1707 then
1708 declare
1709 Type_Def : constant Node_Id :=
1710 Type_Definition (Original_Node (Parent (T_Typ)));
1711 begin
1712 if Nkind (Type_Def) = N_Derived_Type_Definition
1713 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1714 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1715 then
1716 return;
1717 end if;
1718 end;
1719 end if;
1720 end if;
1721
1722 -- Constraint may appear in full view of type
1723
1724 if Ekind (T_Typ) = E_Private_Subtype
1725 and then Present (Full_View (T_Typ))
1726 then
1727 DconT :=
1728 First_Elmt (Discriminant_Constraint (Full_View (T_Typ)));
1729 else
1730 DconT :=
1731 First_Elmt (Discriminant_Constraint (T_Typ));
1732 end if;
1733
1734 while Present (Discr) loop
1735 ItemS := Node (DconS);
1736 ItemT := Node (DconT);
1737
1738 -- For a discriminated component type constrained by the
1739 -- current instance of an enclosing type, there is no
1740 -- applicable discriminant check.
1741
1742 if Nkind (ItemT) = N_Attribute_Reference
1743 and then Is_Access_Type (Etype (ItemT))
1744 and then Is_Entity_Name (Prefix (ItemT))
1745 and then Is_Type (Entity (Prefix (ItemT)))
1746 then
1747 return;
1748 end if;
1749
1750 -- If the expressions for the discriminants are identical
1751 -- and it is side-effect free (for now just an entity),
1752 -- this may be a shared constraint, e.g. from a subtype
1753 -- without a constraint introduced as a generic actual.
1754 -- Examine other discriminants if any.
1755
1756 if ItemS = ItemT
1757 and then Is_Entity_Name (ItemS)
1758 then
1759 null;
1760
1761 elsif not Is_OK_Static_Expression (ItemS)
1762 or else not Is_OK_Static_Expression (ItemT)
1763 then
1764 exit;
1765
1766 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1767 if Do_Access then -- needs run-time check.
1768 exit;
1769 else
1770 Apply_Compile_Time_Constraint_Error
1771 (N, "incorrect value for discriminant&??",
1772 CE_Discriminant_Check_Failed, Ent => Discr);
1773 return;
1774 end if;
1775 end if;
1776
1777 Next_Elmt (DconS);
1778 Next_Elmt (DconT);
1779 Next_Discriminant (Discr);
1780 end loop;
1781
1782 if No (Discr) then
1783 return;
1784 end if;
1785 end;
1786 end if;
1787
1788 -- In GNATprove mode, we do not apply the checks
1789
1790 if GNATprove_Mode then
1791 return;
1792 end if;
1793
1794 -- Here we need a discriminant check. First build the expression
1795 -- for the comparisons of the discriminants:
1796
1797 -- (n.disc1 /= typ.disc1) or else
1798 -- (n.disc2 /= typ.disc2) or else
1799 -- ...
1800 -- (n.discn /= typ.discn)
1801
1802 Cond := Build_Discriminant_Checks (N, T_Typ);
1803
1804 -- If Lhs is set and is a parameter, then the condition is guarded by:
1805 -- lhs'constrained and then (condition built above)
1806
1807 if Present (Param_Entity (Lhs)) then
1808 Cond :=
1809 Make_And_Then (Loc,
1810 Left_Opnd =>
1811 Make_Attribute_Reference (Loc,
1812 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1813 Attribute_Name => Name_Constrained),
1814 Right_Opnd => Cond);
1815 end if;
1816
1817 if Do_Access then
1818 Cond := Guard_Access (Cond, Loc, N);
1819 end if;
1820
1821 Insert_Action (N,
1822 Make_Raise_Constraint_Error (Loc,
1823 Condition => Cond,
1824 Reason => CE_Discriminant_Check_Failed));
1825 end Apply_Discriminant_Check;
1826
1827 -------------------------
1828 -- Apply_Divide_Checks --
1829 -------------------------
1830
1831 procedure Apply_Divide_Checks (N : Node_Id) is
1832 Loc : constant Source_Ptr := Sloc (N);
1833 Typ : constant Entity_Id := Etype (N);
1834 Left : constant Node_Id := Left_Opnd (N);
1835 Right : constant Node_Id := Right_Opnd (N);
1836
1837 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1838 -- Current overflow checking mode
1839
1840 LLB : Uint;
1841 Llo : Uint;
1842 Lhi : Uint;
1843 LOK : Boolean;
1844 Rlo : Uint;
1845 Rhi : Uint;
1846 ROK : Boolean;
1847
1848 pragma Warnings (Off, Lhi);
1849 -- Don't actually use this value
1850
1851 begin
1852 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1853 -- operating on signed integer types, then the only thing this routine
1854 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1855 -- procedure will (possibly later on during recursive downward calls),
1856 -- ensure that any needed overflow/division checks are properly applied.
1857
1858 if Mode in Minimized_Or_Eliminated
1859 and then Is_Signed_Integer_Type (Typ)
1860 then
1861 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
1862 return;
1863 end if;
1864
1865 -- Proceed here in SUPPRESSED or CHECKED modes
1866
1867 if Expander_Active
1868 and then not Backend_Divide_Checks_On_Target
1869 and then Check_Needed (Right, Division_Check)
1870 then
1871 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1872
1873 -- Deal with division check
1874
1875 if Do_Division_Check (N)
1876 and then not Division_Checks_Suppressed (Typ)
1877 then
1878 Apply_Division_Check (N, Rlo, Rhi, ROK);
1879 end if;
1880
1881 -- Deal with overflow check
1882
1883 if Do_Overflow_Check (N)
1884 and then not Overflow_Checks_Suppressed (Etype (N))
1885 then
1886 Set_Do_Overflow_Check (N, False);
1887
1888 -- Test for extremely annoying case of xxx'First divided by -1
1889 -- for division of signed integer types (only overflow case).
1890
1891 if Nkind (N) = N_Op_Divide
1892 and then Is_Signed_Integer_Type (Typ)
1893 then
1894 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1895 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1896
1897 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1898 and then
1899 ((not LOK) or else (Llo = LLB))
1900 then
1901 -- Ensure that expressions are not evaluated twice (once
1902 -- for their runtime checks and once for their regular
1903 -- computation).
1904
1905 Force_Evaluation (Left, Mode => Strict);
1906 Force_Evaluation (Right, Mode => Strict);
1907
1908 Insert_Action (N,
1909 Make_Raise_Constraint_Error (Loc,
1910 Condition =>
1911 Make_And_Then (Loc,
1912 Left_Opnd =>
1913 Make_Op_Eq (Loc,
1914 Left_Opnd =>
1915 Duplicate_Subexpr_Move_Checks (Left),
1916 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1917
1918 Right_Opnd =>
1919 Make_Op_Eq (Loc,
1920 Left_Opnd => Duplicate_Subexpr (Right),
1921 Right_Opnd => Make_Integer_Literal (Loc, -1))),
1922
1923 Reason => CE_Overflow_Check_Failed));
1924 end if;
1925 end if;
1926 end if;
1927 end if;
1928 end Apply_Divide_Checks;
1929
1930 --------------------------
1931 -- Apply_Division_Check --
1932 --------------------------
1933
1934 procedure Apply_Division_Check
1935 (N : Node_Id;
1936 Rlo : Uint;
1937 Rhi : Uint;
1938 ROK : Boolean)
1939 is
1940 pragma Assert (Do_Division_Check (N));
1941
1942 Loc : constant Source_Ptr := Sloc (N);
1943 Right : constant Node_Id := Right_Opnd (N);
1944 Opnd : Node_Id;
1945
1946 begin
1947 if Expander_Active
1948 and then not Backend_Divide_Checks_On_Target
1949 and then Check_Needed (Right, Division_Check)
1950
1951 -- See if division by zero possible, and if so generate test. This
1952 -- part of the test is not controlled by the -gnato switch, since it
1953 -- is a Division_Check and not an Overflow_Check.
1954
1955 and then Do_Division_Check (N)
1956 then
1957 Set_Do_Division_Check (N, False);
1958
1959 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1960 if Is_Floating_Point_Type (Etype (N)) then
1961 Opnd := Make_Real_Literal (Loc, Ureal_0);
1962 else
1963 Opnd := Make_Integer_Literal (Loc, 0);
1964 end if;
1965
1966 Insert_Action (N,
1967 Make_Raise_Constraint_Error (Loc,
1968 Condition =>
1969 Make_Op_Eq (Loc,
1970 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1971 Right_Opnd => Opnd),
1972 Reason => CE_Divide_By_Zero));
1973 end if;
1974 end if;
1975 end Apply_Division_Check;
1976
1977 ----------------------------------
1978 -- Apply_Float_Conversion_Check --
1979 ----------------------------------
1980
1981 -- Let F and I be the source and target types of the conversion. The RM
1982 -- specifies that a floating-point value X is rounded to the nearest
1983 -- integer, with halfway cases being rounded away from zero. The rounded
1984 -- value of X is checked against I'Range.
1985
1986 -- The catch in the above paragraph is that there is no good way to know
1987 -- whether the round-to-integer operation resulted in overflow. A remedy is
1988 -- to perform a range check in the floating-point domain instead, however:
1989
1990 -- (1) The bounds may not be known at compile time
1991 -- (2) The check must take into account rounding or truncation.
1992 -- (3) The range of type I may not be exactly representable in F.
1993 -- (4) For the rounding case, the end-points I'First - 0.5 and
1994 -- I'Last + 0.5 may or may not be in range, depending on the
1995 -- sign of I'First and I'Last.
1996 -- (5) X may be a NaN, which will fail any comparison
1997
1998 -- The following steps correctly convert X with rounding:
1999
2000 -- (1) If either I'First or I'Last is not known at compile time, use
2001 -- I'Base instead of I in the next three steps and perform a
2002 -- regular range check against I'Range after conversion.
2003 -- (2) If I'First - 0.5 is representable in F then let Lo be that
2004 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
2005 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
2006 -- In other words, take one of the closest floating-point numbers
2007 -- (which is an integer value) to I'First, and see if it is in
2008 -- range or not.
2009 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
2010 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
2011 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
2012 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
2013 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
2014
2015 -- For the truncating case, replace steps (2) and (3) as follows:
2016 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
2017 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
2018 -- Lo_OK be True.
2019 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
2020 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
2021 -- Hi_OK be True.
2022
2023 procedure Apply_Float_Conversion_Check
2024 (Expr : Node_Id;
2025 Target_Typ : Entity_Id)
2026 is
2027 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
2028 HB : constant Node_Id := Type_High_Bound (Target_Typ);
2029 Loc : constant Source_Ptr := Sloc (Expr);
2030 Expr_Type : constant Entity_Id := Base_Type (Etype (Expr));
2031 Target_Base : constant Entity_Id :=
2032 Implementation_Base_Type (Target_Typ);
2033
2034 Par : constant Node_Id := Parent (Expr);
2035 pragma Assert (Nkind (Par) = N_Type_Conversion);
2036 -- Parent of check node, must be a type conversion
2037
2038 Truncate : constant Boolean := Float_Truncate (Par);
2039 Max_Bound : constant Uint :=
2040 UI_Expon
2041 (Machine_Radix_Value (Expr_Type),
2042 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
2043
2044 -- Largest bound, so bound plus or minus half is a machine number of F
2045
2046 Ifirst, Ilast : Uint;
2047 -- Bounds of integer type
2048
2049 Lo, Hi : Ureal;
2050 -- Bounds to check in floating-point domain
2051
2052 Lo_OK, Hi_OK : Boolean;
2053 -- True iff Lo resp. Hi belongs to I'Range
2054
2055 Lo_Chk, Hi_Chk : Node_Id;
2056 -- Expressions that are False iff check fails
2057
2058 Reason : RT_Exception_Code;
2059
2060 begin
2061 -- We do not need checks if we are not generating code (i.e. the full
2062 -- expander is not active). In SPARK mode, we specifically don't want
2063 -- the frontend to expand these checks, which are dealt with directly
2064 -- in the formal verification backend.
2065
2066 if not Expander_Active then
2067 return;
2068 end if;
2069
2070 -- Here we will generate an explicit range check, so we don't want to
2071 -- set the Do_Range check flag, since the range check is taken care of
2072 -- by the code we will generate.
2073
2074 Set_Do_Range_Check (Expr, False);
2075
2076 if not Compile_Time_Known_Value (LB)
2077 or not Compile_Time_Known_Value (HB)
2078 then
2079 declare
2080 -- First check that the value falls in the range of the base type,
2081 -- to prevent overflow during conversion and then perform a
2082 -- regular range check against the (dynamic) bounds.
2083
2084 pragma Assert (Target_Base /= Target_Typ);
2085
2086 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
2087
2088 begin
2089 Apply_Float_Conversion_Check (Expr, Target_Base);
2090 Set_Etype (Temp, Target_Base);
2091
2092 -- Note: Previously the declaration was inserted above the parent
2093 -- of the conversion, apparently as a small optimization for the
2094 -- subequent traversal in Insert_Actions. Unfortunately a similar
2095 -- optimization takes place in Insert_Actions, assuming that the
2096 -- insertion point must be above the expression that creates
2097 -- actions. This is not correct in the presence of conditional
2098 -- expressions, where the insertion must be in the list of actions
2099 -- attached to the current alternative.
2100
2101 Insert_Action (Par,
2102 Make_Object_Declaration (Loc,
2103 Defining_Identifier => Temp,
2104 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
2105 Expression => New_Copy_Tree (Par)),
2106 Suppress => All_Checks);
2107
2108 Insert_Action (Par,
2109 Make_Raise_Constraint_Error (Loc,
2110 Condition =>
2111 Make_Not_In (Loc,
2112 Left_Opnd => New_Occurrence_Of (Temp, Loc),
2113 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
2114 Reason => CE_Range_Check_Failed));
2115 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
2116
2117 return;
2118 end;
2119 end if;
2120
2121 -- Get the (static) bounds of the target type
2122
2123 Ifirst := Expr_Value (LB);
2124 Ilast := Expr_Value (HB);
2125
2126 -- A simple optimization: if the expression is a universal literal,
2127 -- we can do the comparison with the bounds and the conversion to
2128 -- an integer type statically. The range checks are unchanged.
2129
2130 if Nkind (Expr) = N_Real_Literal
2131 and then Etype (Expr) = Universal_Real
2132 and then Is_Integer_Type (Target_Typ)
2133 then
2134 declare
2135 Int_Val : constant Uint := UR_To_Uint (Realval (Expr));
2136
2137 begin
2138 if Int_Val <= Ilast and then Int_Val >= Ifirst then
2139
2140 -- Conversion is safe
2141
2142 Rewrite (Parent (Expr),
2143 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
2144 Analyze_And_Resolve (Parent (Expr), Target_Typ);
2145 return;
2146 end if;
2147 end;
2148 end if;
2149
2150 -- Check against lower bound
2151
2152 if Truncate and then Ifirst > 0 then
2153 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
2154 Lo_OK := False;
2155
2156 elsif Truncate then
2157 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
2158 Lo_OK := True;
2159
2160 elsif abs (Ifirst) < Max_Bound then
2161 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
2162 Lo_OK := (Ifirst > 0);
2163
2164 else
2165 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Expr);
2166 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
2167 end if;
2168
2169 -- Saturate the lower bound to that of the expression's type, because
2170 -- we do not want to create an out-of-range value but we still need to
2171 -- do a comparison to catch NaNs.
2172
2173 if Lo < Expr_Value_R (Type_Low_Bound (Expr_Type)) then
2174 Lo := Expr_Value_R (Type_Low_Bound (Expr_Type));
2175 Lo_OK := True;
2176 end if;
2177
2178 if Lo_OK then
2179
2180 -- Lo_Chk := (X >= Lo)
2181
2182 Lo_Chk := Make_Op_Ge (Loc,
2183 Left_Opnd => Duplicate_Subexpr_No_Checks (Expr),
2184 Right_Opnd => Make_Real_Literal (Loc, Lo));
2185
2186 else
2187 -- Lo_Chk := (X > Lo)
2188
2189 Lo_Chk := Make_Op_Gt (Loc,
2190 Left_Opnd => Duplicate_Subexpr_No_Checks (Expr),
2191 Right_Opnd => Make_Real_Literal (Loc, Lo));
2192 end if;
2193
2194 -- Check against higher bound
2195
2196 if Truncate and then Ilast < 0 then
2197 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
2198 Hi_OK := False;
2199
2200 elsif Truncate then
2201 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
2202 Hi_OK := True;
2203
2204 elsif abs (Ilast) < Max_Bound then
2205 Hi := UR_From_Uint (Ilast) + Ureal_Half;
2206 Hi_OK := (Ilast < 0);
2207 else
2208 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Expr);
2209 Hi_OK := (Hi <= UR_From_Uint (Ilast));
2210 end if;
2211
2212 -- Saturate the higher bound to that of the expression's type, because
2213 -- we do not want to create an out-of-range value but we still need to
2214 -- do a comparison to catch NaNs.
2215
2216 if Hi > Expr_Value_R (Type_High_Bound (Expr_Type)) then
2217 Hi := Expr_Value_R (Type_High_Bound (Expr_Type));
2218 Hi_OK := True;
2219 end if;
2220
2221 if Hi_OK then
2222
2223 -- Hi_Chk := (X <= Hi)
2224
2225 Hi_Chk := Make_Op_Le (Loc,
2226 Left_Opnd => Duplicate_Subexpr_No_Checks (Expr),
2227 Right_Opnd => Make_Real_Literal (Loc, Hi));
2228
2229 else
2230 -- Hi_Chk := (X < Hi)
2231
2232 Hi_Chk := Make_Op_Lt (Loc,
2233 Left_Opnd => Duplicate_Subexpr_No_Checks (Expr),
2234 Right_Opnd => Make_Real_Literal (Loc, Hi));
2235 end if;
2236
2237 -- If the bounds of the target type are the same as those of the base
2238 -- type, the check is an overflow check as a range check is not
2239 -- performed in these cases.
2240
2241 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
2242 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
2243 then
2244 Reason := CE_Overflow_Check_Failed;
2245 else
2246 Reason := CE_Range_Check_Failed;
2247 end if;
2248
2249 -- Raise CE if either conditions does not hold
2250
2251 Insert_Action (Expr,
2252 Make_Raise_Constraint_Error (Loc,
2253 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
2254 Reason => Reason));
2255 end Apply_Float_Conversion_Check;
2256
2257 ------------------------
2258 -- Apply_Length_Check --
2259 ------------------------
2260
2261 procedure Apply_Length_Check
2262 (Expr : Node_Id;
2263 Target_Typ : Entity_Id;
2264 Source_Typ : Entity_Id := Empty)
2265 is
2266 begin
2267 Apply_Selected_Length_Checks
2268 (Expr, Target_Typ, Source_Typ, Do_Static => False);
2269 end Apply_Length_Check;
2270
2271 --------------------------------------
2272 -- Apply_Length_Check_On_Assignment --
2273 --------------------------------------
2274
2275 procedure Apply_Length_Check_On_Assignment
2276 (Expr : Node_Id;
2277 Target_Typ : Entity_Id;
2278 Target : Node_Id;
2279 Source_Typ : Entity_Id := Empty)
2280 is
2281 Assign : constant Node_Id := Parent (Target);
2282
2283 begin
2284 -- No check is needed for the initialization of an object whose
2285 -- nominal subtype is unconstrained.
2286
2287 if Is_Constr_Subt_For_U_Nominal (Target_Typ)
2288 and then Nkind (Parent (Assign)) = N_Freeze_Entity
2289 and then Is_Entity_Name (Target)
2290 and then Entity (Target) = Entity (Parent (Assign))
2291 then
2292 return;
2293 end if;
2294
2295 Apply_Selected_Length_Checks
2296 (Expr, Target_Typ, Source_Typ, Do_Static => False);
2297 end Apply_Length_Check_On_Assignment;
2298
2299 -------------------------------------
2300 -- Apply_Parameter_Aliasing_Checks --
2301 -------------------------------------
2302
2303 procedure Apply_Parameter_Aliasing_Checks
2304 (Call : Node_Id;
2305 Subp : Entity_Id)
2306 is
2307 Loc : constant Source_Ptr := Sloc (Call);
2308
2309 function May_Cause_Aliasing
2310 (Formal_1 : Entity_Id;
2311 Formal_2 : Entity_Id) return Boolean;
2312 -- Determine whether two formal parameters can alias each other
2313 -- depending on their modes.
2314
2315 function Original_Actual (N : Node_Id) return Node_Id;
2316 -- The expander may replace an actual with a temporary for the sake of
2317 -- side effect removal. The temporary may hide a potential aliasing as
2318 -- it does not share the address of the actual. This routine attempts
2319 -- to retrieve the original actual.
2320
2321 procedure Overlap_Check
2322 (Actual_1 : Node_Id;
2323 Actual_2 : Node_Id;
2324 Formal_1 : Entity_Id;
2325 Formal_2 : Entity_Id;
2326 Check : in out Node_Id);
2327 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2328 -- If detailed exception messages are enabled, the check is augmented to
2329 -- provide information about the names of the corresponding formals. See
2330 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2331 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2332 -- Check contains all and-ed simple tests generated so far or remains
2333 -- unchanged in the case of detailed exception messaged.
2334
2335 ------------------------
2336 -- May_Cause_Aliasing --
2337 ------------------------
2338
2339 function May_Cause_Aliasing
2340 (Formal_1 : Entity_Id;
2341 Formal_2 : Entity_Id) return Boolean
2342 is
2343 begin
2344 -- The following combination cannot lead to aliasing
2345
2346 -- Formal 1 Formal 2
2347 -- IN IN
2348
2349 if Ekind (Formal_1) = E_In_Parameter
2350 and then
2351 Ekind (Formal_2) = E_In_Parameter
2352 then
2353 return False;
2354
2355 -- The following combinations may lead to aliasing
2356
2357 -- Formal 1 Formal 2
2358 -- IN OUT
2359 -- IN IN OUT
2360 -- OUT IN
2361 -- OUT IN OUT
2362 -- OUT OUT
2363
2364 else
2365 return True;
2366 end if;
2367 end May_Cause_Aliasing;
2368
2369 ---------------------
2370 -- Original_Actual --
2371 ---------------------
2372
2373 function Original_Actual (N : Node_Id) return Node_Id is
2374 begin
2375 if Nkind (N) = N_Type_Conversion then
2376 return Expression (N);
2377
2378 -- The expander created a temporary to capture the result of a type
2379 -- conversion where the expression is the real actual.
2380
2381 elsif Nkind (N) = N_Identifier
2382 and then Present (Original_Node (N))
2383 and then Nkind (Original_Node (N)) = N_Type_Conversion
2384 then
2385 return Expression (Original_Node (N));
2386 end if;
2387
2388 return N;
2389 end Original_Actual;
2390
2391 -------------------
2392 -- Overlap_Check --
2393 -------------------
2394
2395 procedure Overlap_Check
2396 (Actual_1 : Node_Id;
2397 Actual_2 : Node_Id;
2398 Formal_1 : Entity_Id;
2399 Formal_2 : Entity_Id;
2400 Check : in out Node_Id)
2401 is
2402 Cond : Node_Id;
2403 ID_Casing : constant Casing_Type :=
2404 Identifier_Casing (Source_Index (Current_Sem_Unit));
2405
2406 begin
2407 -- Generate:
2408 -- Actual_1'Overlaps_Storage (Actual_2)
2409
2410 Cond :=
2411 Make_Attribute_Reference (Loc,
2412 Prefix => New_Copy_Tree (Original_Actual (Actual_1)),
2413 Attribute_Name => Name_Overlaps_Storage,
2414 Expressions =>
2415 New_List (New_Copy_Tree (Original_Actual (Actual_2))));
2416
2417 -- Generate the following check when detailed exception messages are
2418 -- enabled:
2419
2420 -- if Actual_1'Overlaps_Storage (Actual_2) then
2421 -- raise Program_Error with <detailed message>;
2422 -- end if;
2423
2424 if Exception_Extra_Info then
2425 Start_String;
2426
2427 -- Do not generate location information for internal calls
2428
2429 if Comes_From_Source (Call) then
2430 Store_String_Chars (Build_Location_String (Loc));
2431 Store_String_Char (' ');
2432 end if;
2433
2434 Store_String_Chars ("aliased parameters, actuals for """);
2435
2436 Get_Name_String (Chars (Formal_1));
2437 Set_Casing (ID_Casing);
2438 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2439
2440 Store_String_Chars (""" and """);
2441
2442 Get_Name_String (Chars (Formal_2));
2443 Set_Casing (ID_Casing);
2444 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2445
2446 Store_String_Chars (""" overlap");
2447
2448 Insert_Action (Call,
2449 Make_If_Statement (Loc,
2450 Condition => Cond,
2451 Then_Statements => New_List (
2452 Make_Raise_Statement (Loc,
2453 Name =>
2454 New_Occurrence_Of (Standard_Program_Error, Loc),
2455 Expression => Make_String_Literal (Loc, End_String)))));
2456
2457 -- Create a sequence of overlapping checks by and-ing them all
2458 -- together.
2459
2460 else
2461 if No (Check) then
2462 Check := Cond;
2463 else
2464 Check :=
2465 Make_And_Then (Loc,
2466 Left_Opnd => Check,
2467 Right_Opnd => Cond);
2468 end if;
2469 end if;
2470 end Overlap_Check;
2471
2472 -- Local variables
2473
2474 Actual_1 : Node_Id;
2475 Actual_2 : Node_Id;
2476 Check : Node_Id;
2477 Formal_1 : Entity_Id;
2478 Formal_2 : Entity_Id;
2479 Orig_Act_1 : Node_Id;
2480 Orig_Act_2 : Node_Id;
2481
2482 -- Start of processing for Apply_Parameter_Aliasing_Checks
2483
2484 begin
2485 Check := Empty;
2486
2487 Actual_1 := First_Actual (Call);
2488 Formal_1 := First_Formal (Subp);
2489 while Present (Actual_1) and then Present (Formal_1) loop
2490 Orig_Act_1 := Original_Actual (Actual_1);
2491
2492 -- Ensure that the actual is an object that is not passed by value.
2493 -- Elementary types are always passed by value, therefore actuals of
2494 -- such types cannot lead to aliasing. An aggregate is an object in
2495 -- Ada 2012, but an actual that is an aggregate cannot overlap with
2496 -- another actual. A type that is By_Reference (such as an array of
2497 -- controlled types) is not subject to the check because any update
2498 -- will be done in place and a subsequent read will always see the
2499 -- correct value, see RM 6.2 (12/3).
2500
2501 if Nkind (Orig_Act_1) = N_Aggregate
2502 or else (Nkind (Orig_Act_1) = N_Qualified_Expression
2503 and then Nkind (Expression (Orig_Act_1)) = N_Aggregate)
2504 then
2505 null;
2506
2507 elsif Is_Object_Reference (Orig_Act_1)
2508 and then not Is_Elementary_Type (Etype (Orig_Act_1))
2509 and then not Is_By_Reference_Type (Etype (Orig_Act_1))
2510 then
2511 Actual_2 := Next_Actual (Actual_1);
2512 Formal_2 := Next_Formal (Formal_1);
2513 while Present (Actual_2) and then Present (Formal_2) loop
2514 Orig_Act_2 := Original_Actual (Actual_2);
2515
2516 -- The other actual we are testing against must also denote
2517 -- a non pass-by-value object. Generate the check only when
2518 -- the mode of the two formals may lead to aliasing.
2519
2520 if Is_Object_Reference (Orig_Act_2)
2521 and then not Is_Elementary_Type (Etype (Orig_Act_2))
2522 and then May_Cause_Aliasing (Formal_1, Formal_2)
2523 then
2524 Remove_Side_Effects (Actual_1);
2525 Remove_Side_Effects (Actual_2);
2526
2527 Overlap_Check
2528 (Actual_1 => Actual_1,
2529 Actual_2 => Actual_2,
2530 Formal_1 => Formal_1,
2531 Formal_2 => Formal_2,
2532 Check => Check);
2533 end if;
2534
2535 Next_Actual (Actual_2);
2536 Next_Formal (Formal_2);
2537 end loop;
2538 end if;
2539
2540 Next_Actual (Actual_1);
2541 Next_Formal (Formal_1);
2542 end loop;
2543
2544 -- Place a simple check right before the call
2545
2546 if Present (Check) and then not Exception_Extra_Info then
2547 Insert_Action (Call,
2548 Make_Raise_Program_Error (Loc,
2549 Condition => Check,
2550 Reason => PE_Aliased_Parameters));
2551 end if;
2552 end Apply_Parameter_Aliasing_Checks;
2553
2554 -------------------------------------
2555 -- Apply_Parameter_Validity_Checks --
2556 -------------------------------------
2557
2558 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id) is
2559 Subp_Decl : Node_Id;
2560
2561 procedure Add_Validity_Check
2562 (Formal : Entity_Id;
2563 Prag_Nam : Name_Id;
2564 For_Result : Boolean := False);
2565 -- Add a single 'Valid[_Scalars] check which verifies the initialization
2566 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
2567 -- Set flag For_Result when to verify the result of a function.
2568
2569 ------------------------
2570 -- Add_Validity_Check --
2571 ------------------------
2572
2573 procedure Add_Validity_Check
2574 (Formal : Entity_Id;
2575 Prag_Nam : Name_Id;
2576 For_Result : Boolean := False)
2577 is
2578 procedure Build_Pre_Post_Condition (Expr : Node_Id);
2579 -- Create a pre/postcondition pragma that tests expression Expr
2580
2581 ------------------------------
2582 -- Build_Pre_Post_Condition --
2583 ------------------------------
2584
2585 procedure Build_Pre_Post_Condition (Expr : Node_Id) is
2586 Loc : constant Source_Ptr := Sloc (Subp);
2587 Decls : List_Id;
2588 Prag : Node_Id;
2589
2590 begin
2591 Prag :=
2592 Make_Pragma (Loc,
2593 Chars => Prag_Nam,
2594 Pragma_Argument_Associations => New_List (
2595 Make_Pragma_Argument_Association (Loc,
2596 Chars => Name_Check,
2597 Expression => Expr)));
2598
2599 -- Add a message unless exception messages are suppressed
2600
2601 if not Exception_Locations_Suppressed then
2602 Append_To (Pragma_Argument_Associations (Prag),
2603 Make_Pragma_Argument_Association (Loc,
2604 Chars => Name_Message,
2605 Expression =>
2606 Make_String_Literal (Loc,
2607 Strval => "failed "
2608 & Get_Name_String (Prag_Nam)
2609 & " from "
2610 & Build_Location_String (Loc))));
2611 end if;
2612
2613 -- Insert the pragma in the tree
2614
2615 if Nkind (Parent (Subp_Decl)) = N_Compilation_Unit then
2616 Add_Global_Declaration (Prag);
2617 Analyze (Prag);
2618
2619 -- PPC pragmas associated with subprogram bodies must be inserted
2620 -- in the declarative part of the body.
2621
2622 elsif Nkind (Subp_Decl) = N_Subprogram_Body then
2623 Decls := Declarations (Subp_Decl);
2624
2625 if No (Decls) then
2626 Decls := New_List;
2627 Set_Declarations (Subp_Decl, Decls);
2628 end if;
2629
2630 Prepend_To (Decls, Prag);
2631 Analyze (Prag);
2632
2633 -- For subprogram declarations insert the PPC pragma right after
2634 -- the declarative node.
2635
2636 else
2637 Insert_After_And_Analyze (Subp_Decl, Prag);
2638 end if;
2639 end Build_Pre_Post_Condition;
2640
2641 -- Local variables
2642
2643 Loc : constant Source_Ptr := Sloc (Subp);
2644 Typ : constant Entity_Id := Etype (Formal);
2645 Check : Node_Id;
2646 Nam : Name_Id;
2647
2648 -- Start of processing for Add_Validity_Check
2649
2650 begin
2651 -- For scalars, generate 'Valid test
2652
2653 if Is_Scalar_Type (Typ) then
2654 Nam := Name_Valid;
2655
2656 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2657
2658 elsif Scalar_Part_Present (Typ) then
2659 Nam := Name_Valid_Scalars;
2660
2661 -- No test needed for other cases (no scalars to test)
2662
2663 else
2664 return;
2665 end if;
2666
2667 -- Step 1: Create the expression to verify the validity of the
2668 -- context.
2669
2670 Check := New_Occurrence_Of (Formal, Loc);
2671
2672 -- When processing a function result, use 'Result. Generate
2673 -- Context'Result
2674
2675 if For_Result then
2676 Check :=
2677 Make_Attribute_Reference (Loc,
2678 Prefix => Check,
2679 Attribute_Name => Name_Result);
2680 end if;
2681
2682 -- Generate:
2683 -- Context['Result]'Valid[_Scalars]
2684
2685 Check :=
2686 Make_Attribute_Reference (Loc,
2687 Prefix => Check,
2688 Attribute_Name => Nam);
2689
2690 -- Step 2: Create a pre or post condition pragma
2691
2692 Build_Pre_Post_Condition (Check);
2693 end Add_Validity_Check;
2694
2695 -- Local variables
2696
2697 Formal : Entity_Id;
2698 Subp_Spec : Node_Id;
2699
2700 -- Start of processing for Apply_Parameter_Validity_Checks
2701
2702 begin
2703 -- Extract the subprogram specification and declaration nodes
2704
2705 Subp_Spec := Parent (Subp);
2706
2707 if Nkind (Subp_Spec) = N_Defining_Program_Unit_Name then
2708 Subp_Spec := Parent (Subp_Spec);
2709 end if;
2710
2711 Subp_Decl := Parent (Subp_Spec);
2712
2713 if not Comes_From_Source (Subp)
2714
2715 -- Do not process formal subprograms because the corresponding actual
2716 -- will receive the proper checks when the instance is analyzed.
2717
2718 or else Is_Formal_Subprogram (Subp)
2719
2720 -- Do not process imported subprograms since pre and postconditions
2721 -- are never verified on routines coming from a different language.
2722
2723 or else Is_Imported (Subp)
2724 or else Is_Intrinsic_Subprogram (Subp)
2725
2726 -- The PPC pragmas generated by this routine do not correspond to
2727 -- source aspects, therefore they cannot be applied to abstract
2728 -- subprograms.
2729
2730 or else Nkind (Subp_Decl) = N_Abstract_Subprogram_Declaration
2731
2732 -- Do not consider subprogram renaminds because the renamed entity
2733 -- already has the proper PPC pragmas.
2734
2735 or else Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
2736
2737 -- Do not process null procedures because there is no benefit of
2738 -- adding the checks to a no action routine.
2739
2740 or else (Nkind (Subp_Spec) = N_Procedure_Specification
2741 and then Null_Present (Subp_Spec))
2742 then
2743 return;
2744 end if;
2745
2746 -- Inspect all the formals applying aliasing and scalar initialization
2747 -- checks where applicable.
2748
2749 Formal := First_Formal (Subp);
2750 while Present (Formal) loop
2751
2752 -- Generate the following scalar initialization checks for each
2753 -- formal parameter:
2754
2755 -- mode IN - Pre => Formal'Valid[_Scalars]
2756 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2757 -- mode OUT - Post => Formal'Valid[_Scalars]
2758
2759 if Ekind (Formal) in E_In_Parameter | E_In_Out_Parameter then
2760 Add_Validity_Check (Formal, Name_Precondition, False);
2761 end if;
2762
2763 if Ekind (Formal) in E_In_Out_Parameter | E_Out_Parameter then
2764 Add_Validity_Check (Formal, Name_Postcondition, False);
2765 end if;
2766
2767 Next_Formal (Formal);
2768 end loop;
2769
2770 -- Generate following scalar initialization check for function result:
2771
2772 -- Post => Subp'Result'Valid[_Scalars]
2773
2774 if Ekind (Subp) = E_Function then
2775 Add_Validity_Check (Subp, Name_Postcondition, True);
2776 end if;
2777 end Apply_Parameter_Validity_Checks;
2778
2779 ---------------------------
2780 -- Apply_Predicate_Check --
2781 ---------------------------
2782
2783 procedure Apply_Predicate_Check
2784 (N : Node_Id;
2785 Typ : Entity_Id;
2786 Fun : Entity_Id := Empty)
2787 is
2788 Par : Node_Id;
2789 S : Entity_Id;
2790
2791 Check_Disabled : constant Boolean := (not Predicate_Enabled (Typ))
2792 or else not Predicate_Check_In_Scope (N);
2793 begin
2794 S := Current_Scope;
2795 while Present (S) and then not Is_Subprogram (S) loop
2796 S := Scope (S);
2797 end loop;
2798
2799 -- If the check appears within the predicate function itself, it means
2800 -- that the user specified a check whose formal is the predicated
2801 -- subtype itself, rather than some covering type. This is likely to be
2802 -- a common error, and thus deserves a warning. We want to emit this
2803 -- warning even if predicate checking is disabled (in which case the
2804 -- warning is still useful even if it is not strictly accurate).
2805
2806 if Present (S) and then S = Predicate_Function (Typ) then
2807 Error_Msg_NE
2808 ("predicate check includes a call to& that requires a "
2809 & "predicate check??", Parent (N), Fun);
2810 Error_Msg_N
2811 ("\this will result in infinite recursion??", Parent (N));
2812
2813 if Is_First_Subtype (Typ) then
2814 Error_Msg_NE
2815 ("\use an explicit subtype of& to carry the predicate",
2816 Parent (N), Typ);
2817 end if;
2818
2819 if not Check_Disabled then
2820 Insert_Action (N,
2821 Make_Raise_Storage_Error (Sloc (N),
2822 Reason => SE_Infinite_Recursion));
2823 return;
2824 end if;
2825 end if;
2826
2827 if Check_Disabled then
2828 return;
2829 end if;
2830
2831 -- Normal case of predicate active
2832
2833 -- If the expression is an IN parameter, the predicate will have
2834 -- been applied at the point of call. An additional check would
2835 -- be redundant, or will lead to out-of-scope references if the
2836 -- call appears within an aspect specification for a precondition.
2837
2838 -- However, if the reference is within the body of the subprogram
2839 -- that declares the formal, the predicate can safely be applied,
2840 -- which may be necessary for a nested call whose formal has a
2841 -- different predicate.
2842
2843 if Is_Entity_Name (N)
2844 and then Ekind (Entity (N)) = E_In_Parameter
2845 then
2846 declare
2847 In_Body : Boolean := False;
2848 P : Node_Id := Parent (N);
2849
2850 begin
2851 while Present (P) loop
2852 if Nkind (P) = N_Subprogram_Body
2853 and then
2854 ((Present (Corresponding_Spec (P))
2855 and then
2856 Corresponding_Spec (P) = Scope (Entity (N)))
2857 or else
2858 Defining_Unit_Name (Specification (P)) =
2859 Scope (Entity (N)))
2860 then
2861 In_Body := True;
2862 exit;
2863 end if;
2864
2865 P := Parent (P);
2866 end loop;
2867
2868 if not In_Body then
2869 return;
2870 end if;
2871 end;
2872 end if;
2873
2874 -- If the type has a static predicate and the expression is known
2875 -- at compile time, see if the expression satisfies the predicate.
2876
2877 Check_Expression_Against_Static_Predicate (N, Typ);
2878
2879 if not Expander_Active then
2880 return;
2881 end if;
2882
2883 Par := Parent (N);
2884 if Nkind (Par) = N_Qualified_Expression then
2885 Par := Parent (Par);
2886 end if;
2887
2888 -- For an entity of the type, generate a call to the predicate
2889 -- function, unless its type is an actual subtype, which is not
2890 -- visible outside of the enclosing subprogram.
2891
2892 if Is_Entity_Name (N)
2893 and then not Is_Actual_Subtype (Typ)
2894 then
2895 Insert_Action (N,
2896 Make_Predicate_Check
2897 (Typ, New_Occurrence_Of (Entity (N), Sloc (N))));
2898 return;
2899
2900 elsif Nkind (N) in N_Aggregate | N_Extension_Aggregate then
2901
2902 -- If the expression is an aggregate in an assignment, apply the
2903 -- check to the LHS after the assignment, rather than create a
2904 -- redundant temporary. This is only necessary in rare cases
2905 -- of array types (including strings) initialized with an
2906 -- aggregate with an "others" clause, either coming from source
2907 -- or generated by an Initialize_Scalars pragma.
2908
2909 if Nkind (Par) = N_Assignment_Statement then
2910 Insert_Action_After (Par,
2911 Make_Predicate_Check
2912 (Typ, Duplicate_Subexpr (Name (Par))));
2913 return;
2914
2915 -- Similarly, if the expression is an aggregate in an object
2916 -- declaration, apply it to the object after the declaration.
2917 -- This is only necessary in rare cases of tagged extensions
2918 -- initialized with an aggregate with an "others => <>" clause.
2919
2920 elsif Nkind (Par) = N_Object_Declaration then
2921 Insert_Action_After (Par,
2922 Make_Predicate_Check (Typ,
2923 New_Occurrence_Of (Defining_Identifier (Par), Sloc (N))));
2924 return;
2925 end if;
2926 end if;
2927
2928 -- If the expression is not an entity it may have side effects,
2929 -- and the following call will create an object declaration for
2930 -- it. We disable checks during its analysis, to prevent an
2931 -- infinite recursion.
2932
2933 Insert_Action (N,
2934 Make_Predicate_Check
2935 (Typ, Duplicate_Subexpr (N)), Suppress => All_Checks);
2936 end Apply_Predicate_Check;
2937
2938 -----------------------
2939 -- Apply_Range_Check --
2940 -----------------------
2941
2942 procedure Apply_Range_Check
2943 (Expr : Node_Id;
2944 Target_Typ : Entity_Id;
2945 Source_Typ : Entity_Id := Empty;
2946 Insert_Node : Node_Id := Empty)
2947 is
2948 Checks_On : constant Boolean :=
2949 not Index_Checks_Suppressed (Target_Typ)
2950 or else
2951 not Range_Checks_Suppressed (Target_Typ);
2952
2953 Loc : constant Source_Ptr := Sloc (Expr);
2954
2955 Cond : Node_Id;
2956 R_Cno : Node_Id;
2957 R_Result : Check_Result;
2958
2959 begin
2960 -- Only apply checks when generating code. In GNATprove mode, we do not
2961 -- apply the checks, but we still call Selected_Range_Checks to possibly
2962 -- issue errors on SPARK code when a run-time error can be detected at
2963 -- compile time.
2964
2965 if not GNATprove_Mode then
2966 if not Expander_Active or not Checks_On then
2967 return;
2968 end if;
2969 end if;
2970
2971 R_Result :=
2972 Selected_Range_Checks (Expr, Target_Typ, Source_Typ, Insert_Node);
2973
2974 if GNATprove_Mode then
2975 return;
2976 end if;
2977
2978 for J in 1 .. 2 loop
2979 R_Cno := R_Result (J);
2980 exit when No (R_Cno);
2981
2982 -- The range check requires runtime evaluation. Depending on what its
2983 -- triggering condition is, the check may be converted into a compile
2984 -- time constraint check.
2985
2986 if Nkind (R_Cno) = N_Raise_Constraint_Error
2987 and then Present (Condition (R_Cno))
2988 then
2989 Cond := Condition (R_Cno);
2990
2991 -- Insert the range check before the related context. Note that
2992 -- this action analyses the triggering condition.
2993
2994 if Present (Insert_Node) then
2995 Insert_Action (Insert_Node, R_Cno);
2996 else
2997 Insert_Action (Expr, R_Cno);
2998 end if;
2999
3000 -- The triggering condition evaluates to True, the range check
3001 -- can be converted into a compile time constraint check.
3002
3003 if Is_Entity_Name (Cond)
3004 and then Entity (Cond) = Standard_True
3005 then
3006 -- Since an N_Range is technically not an expression, we have
3007 -- to set one of the bounds to C_E and then just flag the
3008 -- N_Range. The warning message will point to the lower bound
3009 -- and complain about a range, which seems OK.
3010
3011 if Nkind (Expr) = N_Range then
3012 Apply_Compile_Time_Constraint_Error
3013 (Low_Bound (Expr),
3014 "static range out of bounds of}??",
3015 CE_Range_Check_Failed,
3016 Ent => Target_Typ,
3017 Typ => Target_Typ);
3018
3019 Set_Raises_Constraint_Error (Expr);
3020
3021 else
3022 Apply_Compile_Time_Constraint_Error
3023 (Expr,
3024 "static value out of range of}??",
3025 CE_Range_Check_Failed,
3026 Ent => Target_Typ,
3027 Typ => Target_Typ);
3028 end if;
3029 end if;
3030
3031 -- The range check raises Constraint_Error explicitly
3032
3033 elsif Present (Insert_Node) then
3034 R_Cno :=
3035 Make_Raise_Constraint_Error (Sloc (Insert_Node),
3036 Reason => CE_Range_Check_Failed);
3037
3038 Insert_Action (Insert_Node, R_Cno);
3039
3040 else
3041 Install_Static_Check (R_Cno, Loc);
3042 end if;
3043 end loop;
3044 end Apply_Range_Check;
3045
3046 ------------------------------
3047 -- Apply_Scalar_Range_Check --
3048 ------------------------------
3049
3050 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
3051 -- off if it is already set on.
3052
3053 procedure Apply_Scalar_Range_Check
3054 (Expr : Node_Id;
3055 Target_Typ : Entity_Id;
3056 Source_Typ : Entity_Id := Empty;
3057 Fixed_Int : Boolean := False)
3058 is
3059 Parnt : constant Node_Id := Parent (Expr);
3060 S_Typ : Entity_Id;
3061 Arr : Node_Id := Empty; -- initialize to prevent warning
3062 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
3063
3064 Is_Subscr_Ref : Boolean;
3065 -- Set true if Expr is a subscript
3066
3067 Is_Unconstrained_Subscr_Ref : Boolean;
3068 -- Set true if Expr is a subscript of an unconstrained array. In this
3069 -- case we do not attempt to do an analysis of the value against the
3070 -- range of the subscript, since we don't know the actual subtype.
3071
3072 Int_Real : Boolean;
3073 -- Set to True if Expr should be regarded as a real value even though
3074 -- the type of Expr might be discrete.
3075
3076 procedure Bad_Value (Warn : Boolean := False);
3077 -- Procedure called if value is determined to be out of range. Warn is
3078 -- True to force a warning instead of an error, even when SPARK_Mode is
3079 -- On.
3080
3081 ---------------
3082 -- Bad_Value --
3083 ---------------
3084
3085 procedure Bad_Value (Warn : Boolean := False) is
3086 begin
3087 Apply_Compile_Time_Constraint_Error
3088 (Expr, "value not in range of}??", CE_Range_Check_Failed,
3089 Ent => Target_Typ,
3090 Typ => Target_Typ,
3091 Warn => Warn);
3092 end Bad_Value;
3093
3094 -- Start of processing for Apply_Scalar_Range_Check
3095
3096 begin
3097 -- Return if check obviously not needed
3098
3099 if
3100 -- Not needed inside generic
3101
3102 Inside_A_Generic
3103
3104 -- Not needed if previous error
3105
3106 or else Target_Typ = Any_Type
3107 or else Nkind (Expr) = N_Error
3108
3109 -- Not needed for non-scalar type
3110
3111 or else not Is_Scalar_Type (Target_Typ)
3112
3113 -- Not needed if we know node raises CE already
3114
3115 or else Raises_Constraint_Error (Expr)
3116 then
3117 return;
3118 end if;
3119
3120 -- Now, see if checks are suppressed
3121
3122 Is_Subscr_Ref :=
3123 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
3124
3125 if Is_Subscr_Ref then
3126 Arr := Prefix (Parnt);
3127 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
3128
3129 if Is_Access_Type (Arr_Typ) then
3130 Arr_Typ := Designated_Type (Arr_Typ);
3131 end if;
3132 end if;
3133
3134 if not Do_Range_Check (Expr) then
3135
3136 -- Subscript reference. Check for Index_Checks suppressed
3137
3138 if Is_Subscr_Ref then
3139
3140 -- Check array type and its base type
3141
3142 if Index_Checks_Suppressed (Arr_Typ)
3143 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
3144 then
3145 return;
3146
3147 -- Check array itself if it is an entity name
3148
3149 elsif Is_Entity_Name (Arr)
3150 and then Index_Checks_Suppressed (Entity (Arr))
3151 then
3152 return;
3153
3154 -- Check expression itself if it is an entity name
3155
3156 elsif Is_Entity_Name (Expr)
3157 and then Index_Checks_Suppressed (Entity (Expr))
3158 then
3159 return;
3160 end if;
3161
3162 -- All other cases, check for Range_Checks suppressed
3163
3164 else
3165 -- Check target type and its base type
3166
3167 if Range_Checks_Suppressed (Target_Typ)
3168 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
3169 then
3170 return;
3171
3172 -- Check expression itself if it is an entity name
3173
3174 elsif Is_Entity_Name (Expr)
3175 and then Range_Checks_Suppressed (Entity (Expr))
3176 then
3177 return;
3178
3179 -- If Expr is part of an assignment statement, then check left
3180 -- side of assignment if it is an entity name.
3181
3182 elsif Nkind (Parnt) = N_Assignment_Statement
3183 and then Is_Entity_Name (Name (Parnt))
3184 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
3185 then
3186 return;
3187 end if;
3188 end if;
3189 end if;
3190
3191 -- Do not set range checks if they are killed
3192
3193 if Nkind (Expr) = N_Unchecked_Type_Conversion
3194 and then Kill_Range_Check (Expr)
3195 then
3196 return;
3197 end if;
3198
3199 -- Do not set range checks for any values from System.Scalar_Values
3200 -- since the whole idea of such values is to avoid checking them.
3201
3202 if Is_Entity_Name (Expr)
3203 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
3204 then
3205 return;
3206 end if;
3207
3208 -- Now see if we need a check
3209
3210 if No (Source_Typ) then
3211 S_Typ := Etype (Expr);
3212 else
3213 S_Typ := Source_Typ;
3214 end if;
3215
3216 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
3217 return;
3218 end if;
3219
3220 Is_Unconstrained_Subscr_Ref :=
3221 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
3222
3223 -- Special checks for floating-point type
3224
3225 if Is_Floating_Point_Type (S_Typ) then
3226
3227 -- Always do a range check if the source type includes infinities and
3228 -- the target type does not include infinities. We do not do this if
3229 -- range checks are killed.
3230 -- If the expression is a literal and the bounds of the type are
3231 -- static constants it may be possible to optimize the check.
3232
3233 if Has_Infinities (S_Typ)
3234 and then not Has_Infinities (Target_Typ)
3235 then
3236 -- If the expression is a literal and the bounds of the type are
3237 -- static constants it may be possible to optimize the check.
3238
3239 if Nkind (Expr) = N_Real_Literal then
3240 declare
3241 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
3242 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
3243
3244 begin
3245 if Compile_Time_Known_Value (Tlo)
3246 and then Compile_Time_Known_Value (Thi)
3247 and then Expr_Value_R (Expr) >= Expr_Value_R (Tlo)
3248 and then Expr_Value_R (Expr) <= Expr_Value_R (Thi)
3249 then
3250 return;
3251 else
3252 Enable_Range_Check (Expr);
3253 end if;
3254 end;
3255
3256 else
3257 Enable_Range_Check (Expr);
3258 end if;
3259 end if;
3260 end if;
3261
3262 -- Return if we know expression is definitely in the range of the target
3263 -- type as determined by Determine_Range_To_Discrete. Right now we only
3264 -- do this for discrete target types, i.e. neither for fixed-point nor
3265 -- for floating-point types. But the additional less precise tests below
3266 -- catch these cases.
3267
3268 -- Note: skip this if we are given a source_typ, since the point of
3269 -- supplying a Source_Typ is to stop us looking at the expression.
3270 -- We could sharpen this test to be out parameters only ???
3271
3272 if Is_Discrete_Type (Target_Typ)
3273 and then not Is_Unconstrained_Subscr_Ref
3274 and then No (Source_Typ)
3275 then
3276 declare
3277 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
3278 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
3279
3280 begin
3281 if Compile_Time_Known_Value (Tlo)
3282 and then Compile_Time_Known_Value (Thi)
3283 then
3284 declare
3285 OK : Boolean := False; -- initialize to prevent warning
3286 Hiv : constant Uint := Expr_Value (Thi);
3287 Lov : constant Uint := Expr_Value (Tlo);
3288 Hi : Uint := No_Uint;
3289 Lo : Uint := No_Uint;
3290
3291 begin
3292 -- If range is null, we for sure have a constraint error (we
3293 -- don't even need to look at the value involved, since all
3294 -- possible values will raise CE).
3295
3296 if Lov > Hiv then
3297
3298 -- When SPARK_Mode is On, force a warning instead of
3299 -- an error in that case, as this likely corresponds
3300 -- to deactivated code.
3301
3302 Bad_Value (Warn => SPARK_Mode = On);
3303
3304 -- In GNATprove mode, we enable the range check so that
3305 -- GNATprove will issue a message if it cannot be proved.
3306
3307 if GNATprove_Mode then
3308 Enable_Range_Check (Expr);
3309 end if;
3310
3311 return;
3312 end if;
3313
3314 -- Otherwise determine range of value
3315
3316 Determine_Range_To_Discrete
3317 (Expr, OK, Lo, Hi, Fixed_Int, Assume_Valid => True);
3318
3319 if OK then
3320
3321 -- If definitely in range, all OK
3322
3323 if Lo >= Lov and then Hi <= Hiv then
3324 return;
3325
3326 -- If definitely not in range, warn
3327
3328 elsif Lov > Hi or else Hiv < Lo then
3329
3330 -- Ignore out of range values for System.Priority in
3331 -- CodePeer mode since the actual target compiler may
3332 -- provide a wider range.
3333
3334 if not CodePeer_Mode
3335 or else not Is_RTE (Target_Typ, RE_Priority)
3336 then
3337 Bad_Value;
3338 end if;
3339
3340 return;
3341
3342 -- Otherwise we don't know
3343
3344 else
3345 null;
3346 end if;
3347 end if;
3348 end;
3349 end if;
3350 end;
3351 end if;
3352
3353 Int_Real :=
3354 Is_Floating_Point_Type (S_Typ)
3355 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
3356
3357 -- Check if we can determine at compile time whether Expr is in the
3358 -- range of the target type. Note that if S_Typ is within the bounds
3359 -- of Target_Typ then this must be the case. This check is meaningful
3360 -- only if this is not a conversion between integer and real types,
3361 -- unless for a fixed-point type if Fixed_Int is set.
3362
3363 if not Is_Unconstrained_Subscr_Ref
3364 and then (Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
3365 or else (Fixed_Int and then Is_Discrete_Type (Target_Typ)))
3366 and then
3367 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
3368
3369 -- Also check if the expression itself is in the range of the
3370 -- target type if it is a known at compile time value. We skip
3371 -- this test if S_Typ is set since for OUT and IN OUT parameters
3372 -- the Expr itself is not relevant to the checking.
3373
3374 or else
3375 (No (Source_Typ)
3376 and then Is_In_Range (Expr, Target_Typ,
3377 Assume_Valid => True,
3378 Fixed_Int => Fixed_Int,
3379 Int_Real => Int_Real)))
3380 then
3381 return;
3382
3383 elsif Is_Out_Of_Range (Expr, Target_Typ,
3384 Assume_Valid => True,
3385 Fixed_Int => Fixed_Int,
3386 Int_Real => Int_Real)
3387 then
3388 Bad_Value;
3389 return;
3390
3391 -- Floating-point case
3392 -- In the floating-point case, we only do range checks if the type is
3393 -- constrained. We definitely do NOT want range checks for unconstrained
3394 -- types, since we want to have infinities, except when
3395 -- Check_Float_Overflow is set.
3396
3397 elsif Is_Floating_Point_Type (S_Typ) then
3398 if Is_Constrained (S_Typ) or else Check_Float_Overflow then
3399 Enable_Range_Check (Expr);
3400 end if;
3401
3402 -- For all other cases we enable a range check unconditionally
3403
3404 else
3405 Enable_Range_Check (Expr);
3406 return;
3407 end if;
3408 end Apply_Scalar_Range_Check;
3409
3410 ----------------------------------
3411 -- Apply_Selected_Length_Checks --
3412 ----------------------------------
3413
3414 procedure Apply_Selected_Length_Checks
3415 (Expr : Node_Id;
3416 Target_Typ : Entity_Id;
3417 Source_Typ : Entity_Id;
3418 Do_Static : Boolean)
3419 is
3420 Checks_On : constant Boolean :=
3421 not Index_Checks_Suppressed (Target_Typ)
3422 or else
3423 not Length_Checks_Suppressed (Target_Typ);
3424
3425 Loc : constant Source_Ptr := Sloc (Expr);
3426
3427 Cond : Node_Id;
3428 R_Cno : Node_Id;
3429 R_Result : Check_Result;
3430
3431 begin
3432 -- Only apply checks when generating code
3433
3434 -- Note: this means that we lose some useful warnings if the expander
3435 -- is not active.
3436
3437 if not Expander_Active then
3438 return;
3439 end if;
3440
3441 R_Result :=
3442 Selected_Length_Checks (Expr, Target_Typ, Source_Typ, Empty);
3443
3444 for J in 1 .. 2 loop
3445 R_Cno := R_Result (J);
3446 exit when No (R_Cno);
3447
3448 -- A length check may mention an Itype which is attached to a
3449 -- subsequent node. At the top level in a package this can cause
3450 -- an order-of-elaboration problem, so we make sure that the itype
3451 -- is referenced now.
3452
3453 if Ekind (Current_Scope) = E_Package
3454 and then Is_Compilation_Unit (Current_Scope)
3455 then
3456 Ensure_Defined (Target_Typ, Expr);
3457
3458 if Present (Source_Typ) then
3459 Ensure_Defined (Source_Typ, Expr);
3460
3461 elsif Is_Itype (Etype (Expr)) then
3462 Ensure_Defined (Etype (Expr), Expr);
3463 end if;
3464 end if;
3465
3466 if Nkind (R_Cno) = N_Raise_Constraint_Error
3467 and then Present (Condition (R_Cno))
3468 then
3469 Cond := Condition (R_Cno);
3470
3471 -- Case where node does not now have a dynamic check
3472
3473 if not Has_Dynamic_Length_Check (Expr) then
3474
3475 -- If checks are on, just insert the check
3476
3477 if Checks_On then
3478 Insert_Action (Expr, R_Cno);
3479
3480 if not Do_Static then
3481 Set_Has_Dynamic_Length_Check (Expr);
3482 end if;
3483
3484 -- If checks are off, then analyze the length check after
3485 -- temporarily attaching it to the tree in case the relevant
3486 -- condition can be evaluated at compile time. We still want a
3487 -- compile time warning in this case.
3488
3489 else
3490 Set_Parent (R_Cno, Expr);
3491 Analyze (R_Cno);
3492 end if;
3493 end if;
3494
3495 -- Output a warning if the condition is known to be True
3496
3497 if Is_Entity_Name (Cond)
3498 and then Entity (Cond) = Standard_True
3499 then
3500 Apply_Compile_Time_Constraint_Error
3501 (Expr, "wrong length for array of}??",
3502 CE_Length_Check_Failed,
3503 Ent => Target_Typ,
3504 Typ => Target_Typ);
3505
3506 -- If we were only doing a static check, or if checks are not
3507 -- on, then we want to delete the check, since it is not needed.
3508 -- We do this by replacing the if statement by a null statement
3509
3510 elsif Do_Static or else not Checks_On then
3511 Remove_Warning_Messages (R_Cno);
3512 Rewrite (R_Cno, Make_Null_Statement (Loc));
3513 end if;
3514
3515 else
3516 Install_Static_Check (R_Cno, Loc);
3517 end if;
3518 end loop;
3519 end Apply_Selected_Length_Checks;
3520
3521 -------------------------------
3522 -- Apply_Static_Length_Check --
3523 -------------------------------
3524
3525 procedure Apply_Static_Length_Check
3526 (Expr : Node_Id;
3527 Target_Typ : Entity_Id;
3528 Source_Typ : Entity_Id := Empty)
3529 is
3530 begin
3531 Apply_Selected_Length_Checks
3532 (Expr, Target_Typ, Source_Typ, Do_Static => True);
3533 end Apply_Static_Length_Check;
3534
3535 -------------------------------------
3536 -- Apply_Subscript_Validity_Checks --
3537 -------------------------------------
3538
3539 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
3540 Sub : Node_Id;
3541
3542 begin
3543 pragma Assert (Nkind (Expr) = N_Indexed_Component);
3544
3545 -- Loop through subscripts
3546
3547 Sub := First (Expressions (Expr));
3548 while Present (Sub) loop
3549
3550 -- Check one subscript. Note that we do not worry about enumeration
3551 -- type with holes, since we will convert the value to a Pos value
3552 -- for the subscript, and that convert will do the necessary validity
3553 -- check.
3554
3555 Ensure_Valid (Sub, Holes_OK => True);
3556
3557 -- Move to next subscript
3558
3559 Next (Sub);
3560 end loop;
3561 end Apply_Subscript_Validity_Checks;
3562
3563 ----------------------------------
3564 -- Apply_Type_Conversion_Checks --
3565 ----------------------------------
3566
3567 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
3568 Target_Type : constant Entity_Id := Etype (N);
3569 Target_Base : constant Entity_Id := Base_Type (Target_Type);
3570 Expr : constant Node_Id := Expression (N);
3571
3572 Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
3573 -- Note: if Etype (Expr) is a private type without discriminants, its
3574 -- full view might have discriminants with defaults, so we need the
3575 -- full view here to retrieve the constraints.
3576
3577 procedure Make_Discriminant_Constraint_Check
3578 (Target_Type : Entity_Id;
3579 Expr_Type : Entity_Id);
3580 -- Generate a discriminant check based on the target type and expression
3581 -- type for Expr.
3582
3583 ----------------------------------------
3584 -- Make_Discriminant_Constraint_Check --
3585 ----------------------------------------
3586
3587 procedure Make_Discriminant_Constraint_Check
3588 (Target_Type : Entity_Id;
3589 Expr_Type : Entity_Id)
3590 is
3591 Loc : constant Source_Ptr := Sloc (N);
3592 Cond : Node_Id;
3593 Constraint : Elmt_Id;
3594 Discr_Value : Node_Id;
3595 Discr : Entity_Id;
3596
3597 New_Constraints : constant Elist_Id := New_Elmt_List;
3598 Old_Constraints : constant Elist_Id :=
3599 Discriminant_Constraint (Expr_Type);
3600
3601 begin
3602 -- Build an actual discriminant constraint list using the stored
3603 -- constraint, to verify that the expression of the parent type
3604 -- satisfies the constraints imposed by the (unconstrained) derived
3605 -- type. This applies to value conversions, not to view conversions
3606 -- of tagged types.
3607
3608 Constraint := First_Elmt (Stored_Constraint (Target_Type));
3609 while Present (Constraint) loop
3610 Discr_Value := Node (Constraint);
3611
3612 if Is_Entity_Name (Discr_Value)
3613 and then Ekind (Entity (Discr_Value)) = E_Discriminant
3614 then
3615 Discr := Corresponding_Discriminant (Entity (Discr_Value));
3616
3617 if Present (Discr)
3618 and then Scope (Discr) = Base_Type (Expr_Type)
3619 then
3620 -- Parent is constrained by new discriminant. Obtain
3621 -- Value of original discriminant in expression. If the
3622 -- new discriminant has been used to constrain more than
3623 -- one of the stored discriminants, this will provide the
3624 -- required consistency check.
3625
3626 Append_Elmt
3627 (Make_Selected_Component (Loc,
3628 Prefix =>
3629 Duplicate_Subexpr_No_Checks
3630 (Expr, Name_Req => True),
3631 Selector_Name =>
3632 Make_Identifier (Loc, Chars (Discr))),
3633 New_Constraints);
3634
3635 else
3636 -- Discriminant of more remote ancestor ???
3637
3638 return;
3639 end if;
3640
3641 -- Derived type definition has an explicit value for this
3642 -- stored discriminant.
3643
3644 else
3645 Append_Elmt
3646 (Duplicate_Subexpr_No_Checks (Discr_Value),
3647 New_Constraints);
3648 end if;
3649
3650 Next_Elmt (Constraint);
3651 end loop;
3652
3653 -- Use the unconstrained expression type to retrieve the
3654 -- discriminants of the parent, and apply momentarily the
3655 -- discriminant constraint synthesized above.
3656
3657 -- Note: We use Expr_Type instead of Target_Type since the number of
3658 -- actual discriminants may be different due to the presence of
3659 -- stored discriminants and cause Build_Discriminant_Checks to fail.
3660
3661 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
3662 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
3663 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
3664
3665 -- Conversion between access types requires that we check for null
3666 -- before checking discriminants.
3667
3668 if Is_Access_Type (Etype (Expr)) then
3669 Cond := Make_And_Then (Loc,
3670 Left_Opnd =>
3671 Make_Op_Ne (Loc,
3672 Left_Opnd =>
3673 Duplicate_Subexpr_No_Checks
3674 (Expr, Name_Req => True),
3675 Right_Opnd => Make_Null (Loc)),
3676 Right_Opnd => Cond);
3677 end if;
3678
3679 Insert_Action (N,
3680 Make_Raise_Constraint_Error (Loc,
3681 Condition => Cond,
3682 Reason => CE_Discriminant_Check_Failed));
3683 end Make_Discriminant_Constraint_Check;
3684
3685 -- Start of processing for Apply_Type_Conversion_Checks
3686
3687 begin
3688 if Inside_A_Generic then
3689 return;
3690
3691 -- Skip these checks if serious errors detected, there are some nasty
3692 -- situations of incomplete trees that blow things up.
3693
3694 elsif Serious_Errors_Detected > 0 then
3695 return;
3696
3697 -- Never generate discriminant checks for Unchecked_Union types
3698
3699 elsif Present (Expr_Type)
3700 and then Is_Unchecked_Union (Expr_Type)
3701 then
3702 return;
3703
3704 -- Scalar type conversions of the form Target_Type (Expr) require a
3705 -- range check if we cannot be sure that Expr is in the base type of
3706 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3707 -- are not quite the same condition from an implementation point of
3708 -- view, but clearly the second includes the first.
3709
3710 elsif Is_Scalar_Type (Target_Type) then
3711 declare
3712 Conv_OK : constant Boolean := Conversion_OK (N);
3713 -- If the Conversion_OK flag on the type conversion is set and no
3714 -- floating-point type is involved in the type conversion then
3715 -- fixed-point values must be read as integral values.
3716
3717 Float_To_Int : constant Boolean :=
3718 Is_Floating_Point_Type (Expr_Type)
3719 and then Is_Integer_Type (Target_Type);
3720
3721 begin
3722 if not Overflow_Checks_Suppressed (Target_Base)
3723 and then not Overflow_Checks_Suppressed (Target_Type)
3724 and then not
3725 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
3726 and then not Float_To_Int
3727 then
3728 -- A small optimization: the attribute 'Pos applied to an
3729 -- enumeration type has a known range, even though its type is
3730 -- Universal_Integer. So in numeric conversions it is usually
3731 -- within range of the target integer type. Use the static
3732 -- bounds of the base types to check. Disable this optimization
3733 -- in case of a generic formal discrete type, because we don't
3734 -- necessarily know the upper bound yet.
3735
3736 if Nkind (Expr) = N_Attribute_Reference
3737 and then Attribute_Name (Expr) = Name_Pos
3738 and then Is_Enumeration_Type (Etype (Prefix (Expr)))
3739 and then not Is_Generic_Type (Etype (Prefix (Expr)))
3740 and then Is_Integer_Type (Target_Type)
3741 then
3742 declare
3743 Enum_T : constant Entity_Id :=
3744 Root_Type (Etype (Prefix (Expr)));
3745 Int_T : constant Entity_Id := Base_Type (Target_Type);
3746 Last_I : constant Uint :=
3747 Intval (High_Bound (Scalar_Range (Int_T)));
3748 Last_E : Uint;
3749
3750 begin
3751 -- Character types have no explicit literals, so we use
3752 -- the known number of characters in the type.
3753
3754 if Root_Type (Enum_T) = Standard_Character then
3755 Last_E := UI_From_Int (255);
3756
3757 elsif Enum_T = Standard_Wide_Character
3758 or else Enum_T = Standard_Wide_Wide_Character
3759 then
3760 Last_E := UI_From_Int (65535);
3761
3762 else
3763 Last_E :=
3764 Enumeration_Pos
3765 (Entity (High_Bound (Scalar_Range (Enum_T))));
3766 end if;
3767
3768 if Last_E > Last_I then
3769 Activate_Overflow_Check (N);
3770 end if;
3771 end;
3772 else
3773 Activate_Overflow_Check (N);
3774 end if;
3775 end if;
3776
3777 if not Range_Checks_Suppressed (Target_Type)
3778 and then not Range_Checks_Suppressed (Expr_Type)
3779 then
3780 if Float_To_Int
3781 and then not GNATprove_Mode
3782 then
3783 Apply_Float_Conversion_Check (Expr, Target_Type);
3784 else
3785 -- Raw conversions involving fixed-point types are expanded
3786 -- separately and do not need a Range_Check flag yet, except
3787 -- in GNATprove_Mode where this expansion is not performed.
3788 -- This does not apply to conversion where fixed-point types
3789 -- are treated as integers, which are precisely generated by
3790 -- this expansion.
3791
3792 if GNATprove_Mode
3793 or else Conv_OK
3794 or else (not Is_Fixed_Point_Type (Expr_Type)
3795 and then not Is_Fixed_Point_Type (Target_Type))
3796 then
3797 Apply_Scalar_Range_Check
3798 (Expr, Target_Type, Fixed_Int => Conv_OK);
3799
3800 else
3801 Set_Do_Range_Check (Expr, False);
3802 end if;
3803
3804 -- If the target type has predicates, we need to indicate
3805 -- the need for a check, even if Determine_Range finds that
3806 -- the value is within bounds. This may be the case e.g for
3807 -- a division with a constant denominator.
3808
3809 if Has_Predicates (Target_Type) then
3810 Enable_Range_Check (Expr);
3811 end if;
3812 end if;
3813 end if;
3814 end;
3815
3816 -- Generate discriminant constraint checks for access types on the
3817 -- designated target type's stored constraints.
3818
3819 -- Do we need to generate subtype predicate checks here as well ???
3820
3821 elsif Comes_From_Source (N)
3822 and then Ekind (Target_Type) = E_General_Access_Type
3823
3824 -- Check that both of the designated types have known discriminants,
3825 -- and that such checks on the target type are not suppressed.
3826
3827 and then Has_Discriminants (Directly_Designated_Type (Target_Type))
3828 and then Has_Discriminants (Directly_Designated_Type (Expr_Type))
3829 and then not Discriminant_Checks_Suppressed
3830 (Directly_Designated_Type (Target_Type))
3831
3832 -- Verify the designated type of the target has stored constraints
3833
3834 and then Present
3835 (Stored_Constraint (Directly_Designated_Type (Target_Type)))
3836 then
3837 Make_Discriminant_Constraint_Check
3838 (Target_Type => Directly_Designated_Type (Target_Type),
3839 Expr_Type => Directly_Designated_Type (Expr_Type));
3840
3841 -- Create discriminant checks for the Target_Type's stored constraints
3842
3843 elsif Comes_From_Source (N)
3844 and then not Discriminant_Checks_Suppressed (Target_Type)
3845 and then Is_Record_Type (Target_Type)
3846 and then Is_Derived_Type (Target_Type)
3847 and then not Is_Tagged_Type (Target_Type)
3848 and then not Is_Constrained (Target_Type)
3849 and then Present (Stored_Constraint (Target_Type))
3850 then
3851 Make_Discriminant_Constraint_Check (Target_Type, Expr_Type);
3852
3853 -- For arrays, checks are set now, but conversions are applied during
3854 -- expansion, to take into accounts changes of representation. The
3855 -- checks become range checks on the base type or length checks on the
3856 -- subtype, depending on whether the target type is unconstrained or
3857 -- constrained. Note that the range check is put on the expression of a
3858 -- type conversion, while the length check is put on the type conversion
3859 -- itself.
3860
3861 elsif Is_Array_Type (Target_Type) then
3862 if Is_Constrained (Target_Type) then
3863 Set_Do_Length_Check (N);
3864 else
3865 Set_Do_Range_Check (Expr);
3866 end if;
3867 end if;
3868 end Apply_Type_Conversion_Checks;
3869
3870 ----------------------------------------------
3871 -- Apply_Universal_Integer_Attribute_Checks --
3872 ----------------------------------------------
3873
3874 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
3875 Loc : constant Source_Ptr := Sloc (N);
3876 Typ : constant Entity_Id := Etype (N);
3877
3878 begin
3879 if Inside_A_Generic then
3880 return;
3881
3882 -- Nothing to do if the result type is universal integer
3883
3884 elsif Typ = Universal_Integer then
3885 return;
3886
3887 -- Nothing to do if checks are suppressed
3888
3889 elsif Range_Checks_Suppressed (Typ)
3890 and then Overflow_Checks_Suppressed (Typ)
3891 then
3892 return;
3893
3894 -- Nothing to do if the attribute does not come from source. The
3895 -- internal attributes we generate of this type do not need checks,
3896 -- and furthermore the attempt to check them causes some circular
3897 -- elaboration orders when dealing with packed types.
3898
3899 elsif not Comes_From_Source (N) then
3900 return;
3901
3902 -- If the prefix is a selected component that depends on a discriminant
3903 -- the check may improperly expose a discriminant instead of using
3904 -- the bounds of the object itself. Set the type of the attribute to
3905 -- the base type of the context, so that a check will be imposed when
3906 -- needed (e.g. if the node appears as an index).
3907
3908 elsif Nkind (Prefix (N)) = N_Selected_Component
3909 and then Ekind (Typ) = E_Signed_Integer_Subtype
3910 and then Depends_On_Discriminant (Scalar_Range (Typ))
3911 then
3912 Set_Etype (N, Base_Type (Typ));
3913
3914 -- Otherwise, replace the attribute node with a type conversion node
3915 -- whose expression is the attribute, retyped to universal integer, and
3916 -- whose subtype mark is the target type. The call to analyze this
3917 -- conversion will set range and overflow checks as required for proper
3918 -- detection of an out of range value.
3919
3920 else
3921 Set_Etype (N, Universal_Integer);
3922 Set_Analyzed (N, True);
3923
3924 Rewrite (N,
3925 Make_Type_Conversion (Loc,
3926 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
3927 Expression => Relocate_Node (N)));
3928
3929 Analyze_And_Resolve (N, Typ);
3930 return;
3931 end if;
3932 end Apply_Universal_Integer_Attribute_Checks;
3933
3934 -------------------------------------
3935 -- Atomic_Synchronization_Disabled --
3936 -------------------------------------
3937
3938 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3939 -- using a bogus check called Atomic_Synchronization. This is to make it
3940 -- more convenient to get exactly the same semantics as [Un]Suppress.
3941
3942 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
3943 begin
3944 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3945 -- looks enabled, since it is never disabled.
3946
3947 if Debug_Flag_Dot_E then
3948 return False;
3949
3950 -- If debug flag d.d is set then always return True, i.e. all atomic
3951 -- sync looks disabled, since it always tests True.
3952
3953 elsif Debug_Flag_Dot_D then
3954 return True;
3955
3956 -- If entity present, then check result for that entity
3957
3958 elsif Present (E) and then Checks_May_Be_Suppressed (E) then
3959 return Is_Check_Suppressed (E, Atomic_Synchronization);
3960
3961 -- Otherwise result depends on current scope setting
3962
3963 else
3964 return Scope_Suppress.Suppress (Atomic_Synchronization);
3965 end if;
3966 end Atomic_Synchronization_Disabled;
3967
3968 -------------------------------
3969 -- Build_Discriminant_Checks --
3970 -------------------------------
3971
3972 function Build_Discriminant_Checks
3973 (N : Node_Id;
3974 T_Typ : Entity_Id) return Node_Id
3975 is
3976 Loc : constant Source_Ptr := Sloc (N);
3977 Cond : Node_Id;
3978 Disc : Elmt_Id;
3979 Disc_Ent : Entity_Id;
3980 Dref : Node_Id;
3981 Dval : Node_Id;
3982
3983 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
3984
3985 function Replace_Current_Instance
3986 (N : Node_Id) return Traverse_Result;
3987 -- Replace a reference to the current instance of the type with the
3988 -- corresponding _init formal of the initialization procedure. Note:
3989 -- this function relies on us currently being within the initialization
3990 -- procedure.
3991
3992 --------------------------------
3993 -- Aggregate_Discriminant_Val --
3994 --------------------------------
3995
3996 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
3997 Assoc : Node_Id;
3998
3999 begin
4000 -- The aggregate has been normalized with named associations. We use
4001 -- the Chars field to locate the discriminant to take into account
4002 -- discriminants in derived types, which carry the same name as those
4003 -- in the parent.
4004
4005 Assoc := First (Component_Associations (N));
4006 while Present (Assoc) loop
4007 if Chars (First (Choices (Assoc))) = Chars (Disc) then
4008 return Expression (Assoc);
4009 else
4010 Next (Assoc);
4011 end if;
4012 end loop;
4013
4014 -- Discriminant must have been found in the loop above
4015
4016 raise Program_Error;
4017 end Aggregate_Discriminant_Val;
4018
4019 ------------------------------
4020 -- Replace_Current_Instance --
4021 ------------------------------
4022
4023 function Replace_Current_Instance
4024 (N : Node_Id) return Traverse_Result is
4025 begin
4026 if Is_Entity_Name (N)
4027 and then Etype (N) = Entity (N)
4028 then
4029 Rewrite (N,
4030 New_Occurrence_Of (First_Formal (Current_Subprogram), Loc));
4031 end if;
4032
4033 return OK;
4034 end Replace_Current_Instance;
4035
4036 procedure Search_And_Replace_Current_Instance is new
4037 Traverse_Proc (Replace_Current_Instance);
4038
4039 -- Start of processing for Build_Discriminant_Checks
4040
4041 begin
4042 -- Loop through discriminants evolving the condition
4043
4044 Cond := Empty;
4045 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
4046
4047 -- For a fully private type, use the discriminants of the parent type
4048
4049 if Is_Private_Type (T_Typ)
4050 and then No (Full_View (T_Typ))
4051 then
4052 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
4053 else
4054 Disc_Ent := First_Discriminant (T_Typ);
4055 end if;
4056
4057 while Present (Disc) loop
4058 Dval := Node (Disc);
4059
4060 if Nkind (Dval) = N_Identifier
4061 and then Ekind (Entity (Dval)) = E_Discriminant
4062 then
4063 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
4064 else
4065 Dval := Duplicate_Subexpr_No_Checks (Dval);
4066 end if;
4067
4068 -- Replace references to the current instance of the type with the
4069 -- corresponding _init formal of the initialization procedure.
4070
4071 if Within_Init_Proc then
4072 Search_And_Replace_Current_Instance (Dval);
4073 end if;
4074
4075 -- If we have an Unchecked_Union node, we can infer the discriminants
4076 -- of the node.
4077
4078 if Is_Unchecked_Union (Base_Type (T_Typ)) then
4079 Dref := New_Copy (
4080 Get_Discriminant_Value (
4081 First_Discriminant (T_Typ),
4082 T_Typ,
4083 Stored_Constraint (T_Typ)));
4084
4085 elsif Nkind (N) = N_Aggregate then
4086 Dref :=
4087 Duplicate_Subexpr_No_Checks
4088 (Aggregate_Discriminant_Val (Disc_Ent));
4089
4090 elsif Is_Access_Type (Etype (N)) then
4091 Dref :=
4092 Make_Selected_Component (Loc,
4093 Prefix =>
4094 Make_Explicit_Dereference (Loc,
4095 Duplicate_Subexpr_No_Checks (N, Name_Req => True)),
4096 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
4097
4098 Set_Is_In_Discriminant_Check (Dref);
4099 else
4100 Dref :=
4101 Make_Selected_Component (Loc,
4102 Prefix =>
4103 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
4104 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
4105
4106 Set_Is_In_Discriminant_Check (Dref);
4107 end if;
4108
4109 Evolve_Or_Else (Cond,
4110 Make_Op_Ne (Loc,
4111 Left_Opnd => Dref,
4112 Right_Opnd => Dval));
4113
4114 Next_Elmt (Disc);
4115 Next_Discriminant (Disc_Ent);
4116 end loop;
4117
4118 return Cond;
4119 end Build_Discriminant_Checks;
4120
4121 ------------------
4122 -- Check_Needed --
4123 ------------------
4124
4125 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
4126 N : Node_Id;
4127 P : Node_Id;
4128 K : Node_Kind;
4129 L : Node_Id;
4130 R : Node_Id;
4131
4132 function Left_Expression (Op : Node_Id) return Node_Id;
4133 -- Return the relevant expression from the left operand of the given
4134 -- short circuit form: this is LO itself, except if LO is a qualified
4135 -- expression, a type conversion, or an expression with actions, in
4136 -- which case this is Left_Expression (Expression (LO)).
4137
4138 ---------------------
4139 -- Left_Expression --
4140 ---------------------
4141
4142 function Left_Expression (Op : Node_Id) return Node_Id is
4143 LE : Node_Id := Left_Opnd (Op);
4144 begin
4145 while Nkind (LE) in N_Qualified_Expression
4146 | N_Type_Conversion
4147 | N_Expression_With_Actions
4148 loop
4149 LE := Expression (LE);
4150 end loop;
4151
4152 return LE;
4153 end Left_Expression;
4154
4155 -- Start of processing for Check_Needed
4156
4157 begin
4158 -- Always check if not simple entity
4159
4160 if Nkind (Nod) not in N_Has_Entity
4161 or else not Comes_From_Source (Nod)
4162 then
4163 return True;
4164 end if;
4165
4166 -- Look up tree for short circuit
4167
4168 N := Nod;
4169 loop
4170 P := Parent (N);
4171 K := Nkind (P);
4172
4173 -- Done if out of subexpression (note that we allow generated stuff
4174 -- such as itype declarations in this context, to keep the loop going
4175 -- since we may well have generated such stuff in complex situations.
4176 -- Also done if no parent (probably an error condition, but no point
4177 -- in behaving nasty if we find it).
4178
4179 if No (P)
4180 or else (K not in N_Subexpr and then Comes_From_Source (P))
4181 then
4182 return True;
4183
4184 -- Or/Or Else case, where test is part of the right operand, or is
4185 -- part of one of the actions associated with the right operand, and
4186 -- the left operand is an equality test.
4187
4188 elsif K = N_Op_Or then
4189 exit when N = Right_Opnd (P)
4190 and then Nkind (Left_Expression (P)) = N_Op_Eq;
4191
4192 elsif K = N_Or_Else then
4193 exit when (N = Right_Opnd (P)
4194 or else
4195 (Is_List_Member (N)
4196 and then List_Containing (N) = Actions (P)))
4197 and then Nkind (Left_Expression (P)) = N_Op_Eq;
4198
4199 -- Similar test for the And/And then case, where the left operand
4200 -- is an inequality test.
4201
4202 elsif K = N_Op_And then
4203 exit when N = Right_Opnd (P)
4204 and then Nkind (Left_Expression (P)) = N_Op_Ne;
4205
4206 elsif K = N_And_Then then
4207 exit when (N = Right_Opnd (P)
4208 or else
4209 (Is_List_Member (N)
4210 and then List_Containing (N) = Actions (P)))
4211 and then Nkind (Left_Expression (P)) = N_Op_Ne;
4212 end if;
4213
4214 N := P;
4215 end loop;
4216
4217 -- If we fall through the loop, then we have a conditional with an
4218 -- appropriate test as its left operand, so look further.
4219
4220 L := Left_Expression (P);
4221
4222 -- L is an "=" or "/=" operator: extract its operands
4223
4224 R := Right_Opnd (L);
4225 L := Left_Opnd (L);
4226
4227 -- Left operand of test must match original variable
4228
4229 if Nkind (L) not in N_Has_Entity or else Entity (L) /= Entity (Nod) then
4230 return True;
4231 end if;
4232
4233 -- Right operand of test must be key value (zero or null)
4234
4235 case Check is
4236 when Access_Check =>
4237 if not Known_Null (R) then
4238 return True;
4239 end if;
4240
4241 when Division_Check =>
4242 if not Compile_Time_Known_Value (R)
4243 or else Expr_Value (R) /= Uint_0
4244 then
4245 return True;
4246 end if;
4247
4248 when others =>
4249 raise Program_Error;
4250 end case;
4251
4252 -- Here we have the optimizable case, warn if not short-circuited
4253
4254 if K = N_Op_And or else K = N_Op_Or then
4255 Error_Msg_Warn := SPARK_Mode /= On;
4256
4257 case Check is
4258 when Access_Check =>
4259 if GNATprove_Mode then
4260 Error_Msg_N
4261 ("Constraint_Error might have been raised (access check)",
4262 Parent (Nod));
4263 else
4264 Error_Msg_N
4265 ("Constraint_Error may be raised (access check)??",
4266 Parent (Nod));
4267 end if;
4268
4269 when Division_Check =>
4270 if GNATprove_Mode then
4271 Error_Msg_N
4272 ("Constraint_Error might have been raised (zero divide)",
4273 Parent (Nod));
4274 else
4275 Error_Msg_N
4276 ("Constraint_Error may be raised (zero divide)??",
4277 Parent (Nod));
4278 end if;
4279
4280 when others =>
4281 raise Program_Error;
4282 end case;
4283
4284 if K = N_Op_And then
4285 Error_Msg_N -- CODEFIX
4286 ("use `AND THEN` instead of AND??", P);
4287 else
4288 Error_Msg_N -- CODEFIX
4289 ("use `OR ELSE` instead of OR??", P);
4290 end if;
4291
4292 -- If not short-circuited, we need the check
4293
4294 return True;
4295
4296 -- If short-circuited, we can omit the check
4297
4298 else
4299 return False;
4300 end if;
4301 end Check_Needed;
4302
4303 -----------------------------------
4304 -- Check_Valid_Lvalue_Subscripts --
4305 -----------------------------------
4306
4307 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
4308 begin
4309 -- Skip this if range checks are suppressed
4310
4311 if Range_Checks_Suppressed (Etype (Expr)) then
4312 return;
4313
4314 -- Only do this check for expressions that come from source. We assume
4315 -- that expander generated assignments explicitly include any necessary
4316 -- checks. Note that this is not just an optimization, it avoids
4317 -- infinite recursions.
4318
4319 elsif not Comes_From_Source (Expr) then
4320 return;
4321
4322 -- For a selected component, check the prefix
4323
4324 elsif Nkind (Expr) = N_Selected_Component then
4325 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4326 return;
4327
4328 -- Case of indexed component
4329
4330 elsif Nkind (Expr) = N_Indexed_Component then
4331 Apply_Subscript_Validity_Checks (Expr);
4332
4333 -- Prefix may itself be or contain an indexed component, and these
4334 -- subscripts need checking as well.
4335
4336 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4337 end if;
4338 end Check_Valid_Lvalue_Subscripts;
4339
4340 ----------------------------------
4341 -- Null_Exclusion_Static_Checks --
4342 ----------------------------------
4343
4344 procedure Null_Exclusion_Static_Checks
4345 (N : Node_Id;
4346 Comp : Node_Id := Empty;
4347 Array_Comp : Boolean := False)
4348 is
4349 Has_Null : constant Boolean := Has_Null_Exclusion (N);
4350 Kind : constant Node_Kind := Nkind (N);
4351 Error_Nod : Node_Id;
4352 Expr : Node_Id;
4353 Typ : Entity_Id;
4354
4355 begin
4356 pragma Assert
4357 (Kind in N_Component_Declaration
4358 | N_Discriminant_Specification
4359 | N_Function_Specification
4360 | N_Object_Declaration
4361 | N_Parameter_Specification);
4362
4363 if Kind = N_Function_Specification then
4364 Typ := Etype (Defining_Entity (N));
4365 else
4366 Typ := Etype (Defining_Identifier (N));
4367 end if;
4368
4369 case Kind is
4370 when N_Component_Declaration =>
4371 if Present (Access_Definition (Component_Definition (N))) then
4372 Error_Nod := Component_Definition (N);
4373 else
4374 Error_Nod := Subtype_Indication (Component_Definition (N));
4375 end if;
4376
4377 when N_Discriminant_Specification =>
4378 Error_Nod := Discriminant_Type (N);
4379
4380 when N_Function_Specification =>
4381 Error_Nod := Result_Definition (N);
4382
4383 when N_Object_Declaration =>
4384 Error_Nod := Object_Definition (N);
4385
4386 when N_Parameter_Specification =>
4387 Error_Nod := Parameter_Type (N);
4388
4389 when others =>
4390 raise Program_Error;
4391 end case;
4392
4393 if Has_Null then
4394
4395 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4396 -- applied to an access [sub]type.
4397
4398 if not Is_Access_Type (Typ) then
4399 Error_Msg_N
4400 ("`NOT NULL` allowed only for an access type", Error_Nod);
4401
4402 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
4403 -- be applied to a [sub]type that does not exclude null already.
4404
4405 elsif Can_Never_Be_Null (Typ) and then Comes_From_Source (Typ) then
4406 Error_Msg_NE
4407 ("`NOT NULL` not allowed (& already excludes null)",
4408 Error_Nod, Typ);
4409 end if;
4410 end if;
4411
4412 -- Check that null-excluding objects are always initialized, except for
4413 -- deferred constants, for which the expression will appear in the full
4414 -- declaration.
4415
4416 if Kind = N_Object_Declaration
4417 and then No (Expression (N))
4418 and then not Constant_Present (N)
4419 and then not No_Initialization (N)
4420 then
4421 if Present (Comp) then
4422
4423 -- Specialize the warning message to indicate that we are dealing
4424 -- with an uninitialized composite object that has a defaulted
4425 -- null-excluding component.
4426
4427 Error_Msg_Name_1 := Chars (Defining_Identifier (Comp));
4428 Error_Msg_Name_2 := Chars (Defining_Identifier (N));
4429
4430 Discard_Node
4431 (Compile_Time_Constraint_Error
4432 (N => N,
4433 Msg =>
4434 "(Ada 2005) null-excluding component % of object % must "
4435 & "be initialized??",
4436 Ent => Defining_Identifier (Comp)));
4437
4438 -- This is a case of an array with null-excluding components, so
4439 -- indicate that in the warning.
4440
4441 elsif Array_Comp then
4442 Discard_Node
4443 (Compile_Time_Constraint_Error
4444 (N => N,
4445 Msg =>
4446 "(Ada 2005) null-excluding array components must "
4447 & "be initialized??",
4448 Ent => Defining_Identifier (N)));
4449
4450 -- Normal case of object of a null-excluding access type
4451
4452 else
4453 -- Add an expression that assigns null. This node is needed by
4454 -- Apply_Compile_Time_Constraint_Error, which will replace this
4455 -- with a Constraint_Error node.
4456
4457 Set_Expression (N, Make_Null (Sloc (N)));
4458 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
4459
4460 Apply_Compile_Time_Constraint_Error
4461 (N => Expression (N),
4462 Msg =>
4463 "(Ada 2005) null-excluding objects must be initialized??",
4464 Reason => CE_Null_Not_Allowed);
4465 end if;
4466 end if;
4467
4468 -- Check that a null-excluding component, formal or object is not being
4469 -- assigned a null value. Otherwise generate a warning message and
4470 -- replace Expression (N) by an N_Constraint_Error node.
4471
4472 if Kind /= N_Function_Specification then
4473 Expr := Expression (N);
4474
4475 if Present (Expr) and then Known_Null (Expr) then
4476 case Kind is
4477 when N_Component_Declaration
4478 | N_Discriminant_Specification
4479 =>
4480 Apply_Compile_Time_Constraint_Error
4481 (N => Expr,
4482 Msg =>
4483 "(Ada 2005) NULL not allowed in null-excluding "
4484 & "components??",
4485 Reason => CE_Null_Not_Allowed);
4486
4487 when N_Object_Declaration =>
4488 Apply_Compile_Time_Constraint_Error
4489 (N => Expr,
4490 Msg =>
4491 "(Ada 2005) NULL not allowed in null-excluding "
4492 & "objects??",
4493 Reason => CE_Null_Not_Allowed);
4494
4495 when N_Parameter_Specification =>
4496 Apply_Compile_Time_Constraint_Error
4497 (N => Expr,
4498 Msg =>
4499 "(Ada 2005) NULL not allowed in null-excluding "
4500 & "formals??",
4501 Reason => CE_Null_Not_Allowed);
4502
4503 when others =>
4504 null;
4505 end case;
4506 end if;
4507 end if;
4508 end Null_Exclusion_Static_Checks;
4509
4510 -------------------------------------
4511 -- Compute_Range_For_Arithmetic_Op --
4512 -------------------------------------
4513
4514 procedure Compute_Range_For_Arithmetic_Op
4515 (Op : Node_Kind;
4516 Lo_Left : Uint;
4517 Hi_Left : Uint;
4518 Lo_Right : Uint;
4519 Hi_Right : Uint;
4520 OK : out Boolean;
4521 Lo : out Uint;
4522 Hi : out Uint)
4523 is
4524 -- Use local variables for possible adjustments
4525
4526 Llo : Uint renames Lo_Left;
4527 Lhi : Uint renames Hi_Left;
4528 Rlo : Uint := Lo_Right;
4529 Rhi : Uint := Hi_Right;
4530
4531 begin
4532 -- We will compute a range for the result in almost all cases
4533
4534 OK := True;
4535
4536 case Op is
4537
4538 -- Absolute value
4539
4540 when N_Op_Abs =>
4541 Lo := Uint_0;
4542 Hi := UI_Max (abs Rlo, abs Rhi);
4543
4544 -- Addition
4545
4546 when N_Op_Add =>
4547 Lo := Llo + Rlo;
4548 Hi := Lhi + Rhi;
4549
4550 -- Division
4551
4552 when N_Op_Divide =>
4553
4554 -- If the right operand can only be zero, set 0..0
4555
4556 if Rlo = 0 and then Rhi = 0 then
4557 Lo := Uint_0;
4558 Hi := Uint_0;
4559
4560 -- Possible bounds of division must come from dividing end
4561 -- values of the input ranges (four possibilities), provided
4562 -- zero is not included in the possible values of the right
4563 -- operand.
4564
4565 -- Otherwise, we just consider two intervals of values for
4566 -- the right operand: the interval of negative values (up to
4567 -- -1) and the interval of positive values (starting at 1).
4568 -- Since division by 1 is the identity, and division by -1
4569 -- is negation, we get all possible bounds of division in that
4570 -- case by considering:
4571 -- - all values from the division of end values of input
4572 -- ranges;
4573 -- - the end values of the left operand;
4574 -- - the negation of the end values of the left operand.
4575
4576 else
4577 declare
4578 Mrk : constant Uintp.Save_Mark := Mark;
4579 -- Mark so we can release the RR and Ev values
4580
4581 Ev1 : Uint;
4582 Ev2 : Uint;
4583 Ev3 : Uint;
4584 Ev4 : Uint;
4585
4586 begin
4587 -- Discard extreme values of zero for the divisor, since
4588 -- they will simply result in an exception in any case.
4589
4590 if Rlo = 0 then
4591 Rlo := Uint_1;
4592 elsif Rhi = 0 then
4593 Rhi := -Uint_1;
4594 end if;
4595
4596 -- Compute possible bounds coming from dividing end
4597 -- values of the input ranges.
4598
4599 Ev1 := Llo / Rlo;
4600 Ev2 := Llo / Rhi;
4601 Ev3 := Lhi / Rlo;
4602 Ev4 := Lhi / Rhi;
4603
4604 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
4605 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
4606
4607 -- If the right operand can be both negative or positive,
4608 -- include the end values of the left operand in the
4609 -- extreme values, as well as their negation.
4610
4611 if Rlo < 0 and then Rhi > 0 then
4612 Ev1 := Llo;
4613 Ev2 := -Llo;
4614 Ev3 := Lhi;
4615 Ev4 := -Lhi;
4616
4617 Lo := UI_Min (Lo,
4618 UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4)));
4619 Hi := UI_Max (Hi,
4620 UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4)));
4621 end if;
4622
4623 -- Release the RR and Ev values
4624
4625 Release_And_Save (Mrk, Lo, Hi);
4626 end;
4627 end if;
4628
4629 -- Exponentiation
4630
4631 when N_Op_Expon =>
4632
4633 -- Discard negative values for the exponent, since they will
4634 -- simply result in an exception in any case.
4635
4636 if Rhi < 0 then
4637 Rhi := Uint_0;
4638 elsif Rlo < 0 then
4639 Rlo := Uint_0;
4640 end if;
4641
4642 -- Estimate number of bits in result before we go computing
4643 -- giant useless bounds. Basically the number of bits in the
4644 -- result is the number of bits in the base multiplied by the
4645 -- value of the exponent. If this is big enough that the result
4646 -- definitely won't fit in Long_Long_Integer, return immediately
4647 -- and avoid computing giant bounds.
4648
4649 -- The comparison here is approximate, but conservative, it
4650 -- only clicks on cases that are sure to exceed the bounds.
4651
4652 if Num_Bits (UI_Max (abs Llo, abs Lhi)) * Rhi + 1 > 100 then
4653 Lo := No_Uint;
4654 Hi := No_Uint;
4655 OK := False;
4656 return;
4657
4658 -- If right operand is zero then result is 1
4659
4660 elsif Rhi = 0 then
4661 Lo := Uint_1;
4662 Hi := Uint_1;
4663
4664 else
4665 -- High bound comes either from exponentiation of largest
4666 -- positive value to largest exponent value, or from
4667 -- the exponentiation of most negative value to an
4668 -- even exponent.
4669
4670 declare
4671 Hi1, Hi2 : Uint;
4672
4673 begin
4674 if Lhi > 0 then
4675 Hi1 := Lhi ** Rhi;
4676 else
4677 Hi1 := Uint_0;
4678 end if;
4679
4680 if Llo < 0 then
4681 if Rhi mod 2 = 0 then
4682 Hi2 := Llo ** Rhi;
4683 else
4684 Hi2 := Llo ** (Rhi - 1);
4685 end if;
4686 else
4687 Hi2 := Uint_0;
4688 end if;
4689
4690 Hi := UI_Max (Hi1, Hi2);
4691 end;
4692
4693 -- Result can only be negative if base can be negative
4694
4695 if Llo < 0 then
4696 if Rhi mod 2 = 0 then
4697 Lo := Llo ** (Rhi - 1);
4698 else
4699 Lo := Llo ** Rhi;
4700 end if;
4701
4702 -- Otherwise low bound is minimum ** minimum
4703
4704 else
4705 Lo := Llo ** Rlo;
4706 end if;
4707 end if;
4708
4709 -- Negation
4710
4711 when N_Op_Minus =>
4712 Lo := -Rhi;
4713 Hi := -Rlo;
4714
4715 -- Mod
4716
4717 when N_Op_Mod =>
4718 declare
4719 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
4720 -- This is the maximum absolute value of the result
4721
4722 begin
4723 Lo := Uint_0;
4724 Hi := Uint_0;
4725
4726 -- The result depends only on the sign and magnitude of
4727 -- the right operand, it does not depend on the sign or
4728 -- magnitude of the left operand.
4729
4730 if Rlo < 0 then
4731 Lo := -Maxabs;
4732 end if;
4733
4734 if Rhi > 0 then
4735 Hi := Maxabs;
4736 end if;
4737 end;
4738
4739 -- Multiplication
4740
4741 when N_Op_Multiply =>
4742
4743 -- Possible bounds of multiplication must come from multiplying
4744 -- end values of the input ranges (four possibilities).
4745
4746 declare
4747 Mrk : constant Uintp.Save_Mark := Mark;
4748 -- Mark so we can release the Ev values
4749
4750 Ev1 : constant Uint := Llo * Rlo;
4751 Ev2 : constant Uint := Llo * Rhi;
4752 Ev3 : constant Uint := Lhi * Rlo;
4753 Ev4 : constant Uint := Lhi * Rhi;
4754
4755 begin
4756 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
4757 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
4758
4759 -- Release the Ev values
4760
4761 Release_And_Save (Mrk, Lo, Hi);
4762 end;
4763
4764 -- Plus operator (affirmation)
4765
4766 when N_Op_Plus =>
4767 Lo := Rlo;
4768 Hi := Rhi;
4769
4770 -- Remainder
4771
4772 when N_Op_Rem =>
4773 declare
4774 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
4775 -- This is the maximum absolute value of the result. Note
4776 -- that the result range does not depend on the sign of the
4777 -- right operand.
4778
4779 begin
4780 Lo := Uint_0;
4781 Hi := Uint_0;
4782
4783 -- Case of left operand negative, which results in a range
4784 -- of -Maxabs .. 0 for those negative values. If there are
4785 -- no negative values then Lo value of result is always 0.
4786
4787 if Llo < 0 then
4788 Lo := -Maxabs;
4789 end if;
4790
4791 -- Case of left operand positive
4792
4793 if Lhi > 0 then
4794 Hi := Maxabs;
4795 end if;
4796 end;
4797
4798 -- Subtract
4799
4800 when N_Op_Subtract =>
4801 Lo := Llo - Rhi;
4802 Hi := Lhi - Rlo;
4803
4804 -- Nothing else should be possible
4805
4806 when others =>
4807 raise Program_Error;
4808 end case;
4809 end Compute_Range_For_Arithmetic_Op;
4810
4811 ----------------------------------
4812 -- Conditional_Statements_Begin --
4813 ----------------------------------
4814
4815 procedure Conditional_Statements_Begin is
4816 begin
4817 Saved_Checks_TOS := Saved_Checks_TOS + 1;
4818
4819 -- If stack overflows, kill all checks, that way we know to simply reset
4820 -- the number of saved checks to zero on return. This should never occur
4821 -- in practice.
4822
4823 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4824 Kill_All_Checks;
4825
4826 -- In the normal case, we just make a new stack entry saving the current
4827 -- number of saved checks for a later restore.
4828
4829 else
4830 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
4831
4832 if Debug_Flag_CC then
4833 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
4834 Num_Saved_Checks);
4835 end if;
4836 end if;
4837 end Conditional_Statements_Begin;
4838
4839 --------------------------------
4840 -- Conditional_Statements_End --
4841 --------------------------------
4842
4843 procedure Conditional_Statements_End is
4844 begin
4845 pragma Assert (Saved_Checks_TOS > 0);
4846
4847 -- If the saved checks stack overflowed, then we killed all checks, so
4848 -- setting the number of saved checks back to zero is correct. This
4849 -- should never occur in practice.
4850
4851 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4852 Num_Saved_Checks := 0;
4853
4854 -- In the normal case, restore the number of saved checks from the top
4855 -- stack entry.
4856
4857 else
4858 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
4859
4860 if Debug_Flag_CC then
4861 w ("Conditional_Statements_End: Num_Saved_Checks = ",
4862 Num_Saved_Checks);
4863 end if;
4864 end if;
4865
4866 Saved_Checks_TOS := Saved_Checks_TOS - 1;
4867 end Conditional_Statements_End;
4868
4869 -------------------------
4870 -- Convert_From_Bignum --
4871 -------------------------
4872
4873 function Convert_From_Bignum (N : Node_Id) return Node_Id is
4874 Loc : constant Source_Ptr := Sloc (N);
4875
4876 begin
4877 pragma Assert (Is_RTE (Etype (N), RE_Bignum));
4878
4879 -- Construct call From Bignum
4880
4881 return
4882 Make_Function_Call (Loc,
4883 Name =>
4884 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4885 Parameter_Associations => New_List (Relocate_Node (N)));
4886 end Convert_From_Bignum;
4887
4888 -----------------------
4889 -- Convert_To_Bignum --
4890 -----------------------
4891
4892 function Convert_To_Bignum (N : Node_Id) return Node_Id is
4893 Loc : constant Source_Ptr := Sloc (N);
4894
4895 begin
4896 -- Nothing to do if Bignum already except call Relocate_Node
4897
4898 if Is_RTE (Etype (N), RE_Bignum) then
4899 return Relocate_Node (N);
4900
4901 -- Otherwise construct call to To_Bignum, converting the operand to the
4902 -- required Long_Long_Integer form.
4903
4904 else
4905 pragma Assert (Is_Signed_Integer_Type (Etype (N)));
4906 return
4907 Make_Function_Call (Loc,
4908 Name =>
4909 New_Occurrence_Of (RTE (RE_To_Bignum), Loc),
4910 Parameter_Associations => New_List (
4911 Convert_To (Standard_Long_Long_Integer, Relocate_Node (N))));
4912 end if;
4913 end Convert_To_Bignum;
4914
4915 ---------------------
4916 -- Determine_Range --
4917 ---------------------
4918
4919 Cache_Size : constant := 2 ** 10;
4920 type Cache_Index is range 0 .. Cache_Size - 1;
4921 -- Determine size of below cache (power of 2 is more efficient)
4922
4923 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
4924 Determine_Range_Cache_O : array (Cache_Index) of Node_Id;
4925 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
4926 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
4927 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
4928 Determine_Range_Cache_Lo_R : array (Cache_Index) of Ureal;
4929 Determine_Range_Cache_Hi_R : array (Cache_Index) of Ureal;
4930 -- The above arrays are used to implement a small direct cache for
4931 -- Determine_Range and Determine_Range_R calls. Because of the way these
4932 -- subprograms recursively traces subexpressions, and because overflow
4933 -- checking calls the routine on the way up the tree, a quadratic behavior
4934 -- can otherwise be encountered in large expressions. The cache entry for
4935 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4936 -- by checking the actual node value stored there. The Range_Cache_O array
4937 -- records the setting of Original_Node (N) so that the cache entry does
4938 -- not become stale when the node N is rewritten. The Range_Cache_V array
4939 -- records the setting of Assume_Valid for the cache entry.
4940
4941 procedure Determine_Range
4942 (N : Node_Id;
4943 OK : out Boolean;
4944 Lo : out Uint;
4945 Hi : out Uint;
4946 Assume_Valid : Boolean := False)
4947 is
4948 Kind : constant Node_Kind := Nkind (N);
4949 -- Kind of node
4950
4951 function Half_Address_Space return Uint;
4952 -- The size of half the total addressable memory space in storage units
4953 -- (minus one, so that the size fits in a signed integer whose size is
4954 -- System_Address_Size, which helps in various cases).
4955
4956 ------------------------
4957 -- Half_Address_Space --
4958 ------------------------
4959
4960 function Half_Address_Space return Uint is
4961 begin
4962 return Uint_2 ** (System_Address_Size - 1) - 1;
4963 end Half_Address_Space;
4964
4965 -- Local variables
4966
4967 Typ : Entity_Id := Etype (N);
4968 -- Type to use, may get reset to base type for possibly invalid entity
4969
4970 Lo_Left : Uint := No_Uint;
4971 Hi_Left : Uint := No_Uint;
4972 -- Lo and Hi bounds of left operand
4973
4974 Lo_Right : Uint := No_Uint;
4975 Hi_Right : Uint := No_Uint;
4976 -- Lo and Hi bounds of right (or only) operand
4977
4978 Bound : Node_Id;
4979 -- Temp variable used to hold a bound node
4980
4981 Hbound : Uint;
4982 -- High bound of base type of expression
4983
4984 Lor : Uint;
4985 Hir : Uint;
4986 -- Refined values for low and high bounds, after tightening
4987
4988 OK1 : Boolean;
4989 -- Used in lower level calls to indicate if call succeeded
4990
4991 Cindex : Cache_Index;
4992 -- Used to search cache
4993
4994 Btyp : Entity_Id;
4995 -- Base type
4996
4997 -- Start of processing for Determine_Range
4998
4999 begin
5000 -- Prevent junk warnings by initializing range variables
5001
5002 Lo := No_Uint;
5003 Hi := No_Uint;
5004 Lor := No_Uint;
5005 Hir := No_Uint;
5006
5007 -- For temporary constants internally generated to remove side effects
5008 -- we must use the corresponding expression to determine the range of
5009 -- the expression. But note that the expander can also generate
5010 -- constants in other cases, including deferred constants.
5011
5012 if Is_Entity_Name (N)
5013 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
5014 and then Ekind (Entity (N)) = E_Constant
5015 and then Is_Internal_Name (Chars (Entity (N)))
5016 then
5017 if Present (Expression (Parent (Entity (N)))) then
5018 Determine_Range
5019 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
5020
5021 elsif Present (Full_View (Entity (N))) then
5022 Determine_Range
5023 (Expression (Parent (Full_View (Entity (N)))),
5024 OK, Lo, Hi, Assume_Valid);
5025
5026 else
5027 OK := False;
5028 end if;
5029 return;
5030 end if;
5031
5032 -- If type is not defined, we can't determine its range
5033
5034 if No (Typ)
5035
5036 -- We don't deal with anything except discrete types
5037
5038 or else not Is_Discrete_Type (Typ)
5039
5040 -- Don't deal with enumerated types with non-standard representation
5041
5042 or else (Is_Enumeration_Type (Typ)
5043 and then Present (Enum_Pos_To_Rep (Base_Type (Typ))))
5044
5045 -- Ignore type for which an error has been posted, since range in
5046 -- this case may well be a bogosity deriving from the error. Also
5047 -- ignore if error posted on the reference node.
5048
5049 or else Error_Posted (N) or else Error_Posted (Typ)
5050 then
5051 OK := False;
5052 return;
5053 end if;
5054
5055 -- For all other cases, we can determine the range
5056
5057 OK := True;
5058
5059 -- If value is compile time known, then the possible range is the one
5060 -- value that we know this expression definitely has.
5061
5062 if Compile_Time_Known_Value (N) then
5063 Lo := Expr_Value (N);
5064 Hi := Lo;
5065 return;
5066 end if;
5067
5068 -- Return if already in the cache
5069
5070 Cindex := Cache_Index (N mod Cache_Size);
5071
5072 if Determine_Range_Cache_N (Cindex) = N
5073 and then
5074 Determine_Range_Cache_O (Cindex) = Original_Node (N)
5075 and then
5076 Determine_Range_Cache_V (Cindex) = Assume_Valid
5077 then
5078 Lo := Determine_Range_Cache_Lo (Cindex);
5079 Hi := Determine_Range_Cache_Hi (Cindex);
5080 return;
5081 end if;
5082
5083 -- Otherwise, start by finding the bounds of the type of the expression,
5084 -- the value cannot be outside this range (if it is, then we have an
5085 -- overflow situation, which is a separate check, we are talking here
5086 -- only about the expression value).
5087
5088 -- First a check, never try to find the bounds of a generic type, since
5089 -- these bounds are always junk values, and it is only valid to look at
5090 -- the bounds in an instance.
5091
5092 if Is_Generic_Type (Typ) then
5093 OK := False;
5094 return;
5095 end if;
5096
5097 -- First step, change to use base type unless we know the value is valid
5098
5099 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
5100 or else Assume_No_Invalid_Values
5101 or else Assume_Valid
5102 then
5103 -- If this is a known valid constant with a nonstatic value, it may
5104 -- have inherited a narrower subtype from its initial value; use this
5105 -- saved subtype (see sem_ch3.adb).
5106
5107 if Is_Entity_Name (N)
5108 and then Ekind (Entity (N)) = E_Constant
5109 and then Present (Actual_Subtype (Entity (N)))
5110 then
5111 Typ := Actual_Subtype (Entity (N));
5112 end if;
5113
5114 else
5115 Typ := Underlying_Type (Base_Type (Typ));
5116 end if;
5117
5118 -- Retrieve the base type. Handle the case where the base type is a
5119 -- private enumeration type.
5120
5121 Btyp := Base_Type (Typ);
5122
5123 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
5124 Btyp := Full_View (Btyp);
5125 end if;
5126
5127 -- We use the actual bound unless it is dynamic, in which case use the
5128 -- corresponding base type bound if possible. If we can't get a bound
5129 -- then we figure we can't determine the range (a peculiar case, that
5130 -- perhaps cannot happen, but there is no point in bombing in this
5131 -- optimization circuit).
5132
5133 -- First the low bound
5134
5135 Bound := Type_Low_Bound (Typ);
5136
5137 if Compile_Time_Known_Value (Bound) then
5138 Lo := Expr_Value (Bound);
5139
5140 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
5141 Lo := Expr_Value (Type_Low_Bound (Btyp));
5142
5143 else
5144 OK := False;
5145 return;
5146 end if;
5147
5148 -- Now the high bound
5149
5150 Bound := Type_High_Bound (Typ);
5151
5152 -- We need the high bound of the base type later on, and this should
5153 -- always be compile time known. Again, it is not clear that this
5154 -- can ever be false, but no point in bombing.
5155
5156 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
5157 Hbound := Expr_Value (Type_High_Bound (Btyp));
5158 Hi := Hbound;
5159
5160 else
5161 OK := False;
5162 return;
5163 end if;
5164
5165 -- If we have a static subtype, then that may have a tighter bound so
5166 -- use the upper bound of the subtype instead in this case.
5167
5168 if Compile_Time_Known_Value (Bound) then
5169 Hi := Expr_Value (Bound);
5170 end if;
5171
5172 -- We may be able to refine this value in certain situations. If any
5173 -- refinement is possible, then Lor and Hir are set to possibly tighter
5174 -- bounds, and OK1 is set to True.
5175
5176 case Kind is
5177
5178 -- Unary operation case
5179
5180 when N_Op_Abs
5181 | N_Op_Minus
5182 | N_Op_Plus
5183 =>
5184 Determine_Range
5185 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5186
5187 if OK1 then
5188 Compute_Range_For_Arithmetic_Op
5189 (Kind, Lo_Left, Hi_Left, Lo_Right, Hi_Right, OK1, Lor, Hir);
5190 end if;
5191
5192 -- Binary operation case
5193
5194 when N_Op_Add
5195 | N_Op_Divide
5196 | N_Op_Expon
5197 | N_Op_Mod
5198 | N_Op_Multiply
5199 | N_Op_Rem
5200 | N_Op_Subtract
5201 =>
5202 Determine_Range
5203 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
5204
5205 if OK1 then
5206 Determine_Range
5207 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5208 end if;
5209
5210 if OK1 then
5211 Compute_Range_For_Arithmetic_Op
5212 (Kind, Lo_Left, Hi_Left, Lo_Right, Hi_Right, OK1, Lor, Hir);
5213 end if;
5214
5215 -- Attribute reference cases
5216
5217 when N_Attribute_Reference =>
5218 case Get_Attribute_Id (Attribute_Name (N)) is
5219
5220 -- For Min/Max attributes, we can refine the range using the
5221 -- possible range of values of the attribute expressions.
5222
5223 when Attribute_Min
5224 | Attribute_Max
5225 =>
5226 Determine_Range
5227 (First (Expressions (N)),
5228 OK1, Lo_Left, Hi_Left, Assume_Valid);
5229
5230 if OK1 then
5231 Determine_Range
5232 (Next (First (Expressions (N))),
5233 OK1, Lo_Right, Hi_Right, Assume_Valid);
5234 end if;
5235
5236 if OK1 then
5237 Lor := UI_Min (Lo_Left, Lo_Right);
5238 Hir := UI_Max (Hi_Left, Hi_Right);
5239 end if;
5240
5241 -- For Pos/Val attributes, we can refine the range using the
5242 -- possible range of values of the attribute expression.
5243
5244 when Attribute_Pos
5245 | Attribute_Val
5246 =>
5247 Determine_Range
5248 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
5249
5250 -- For Length and Range_Length attributes, use the bounds of
5251 -- the (corresponding index) type to refine the range.
5252
5253 when Attribute_Length
5254 | Attribute_Range_Length
5255 =>
5256 declare
5257 Ptyp : Entity_Id;
5258 Ityp : Entity_Id;
5259
5260 LL, LU : Uint;
5261 UL, UU : Uint;
5262
5263 begin
5264 Ptyp := Etype (Prefix (N));
5265 if Is_Access_Type (Ptyp) then
5266 Ptyp := Designated_Type (Ptyp);
5267 end if;
5268
5269 -- For string literal, we know exact value
5270
5271 if Ekind (Ptyp) = E_String_Literal_Subtype then
5272 OK := True;
5273 Lo := String_Literal_Length (Ptyp);
5274 Hi := String_Literal_Length (Ptyp);
5275 return;
5276 end if;
5277
5278 if Is_Array_Type (Ptyp) then
5279 Ityp := Get_Index_Subtype (N);
5280 else
5281 Ityp := Ptyp;
5282 end if;
5283
5284 -- If the (index) type is a formal type or derived from
5285 -- one, the bounds are not static.
5286
5287 if Is_Generic_Type (Root_Type (Ityp)) then
5288 OK := False;
5289 return;
5290 end if;
5291
5292 Determine_Range
5293 (Type_Low_Bound (Ityp), OK1, LL, LU, Assume_Valid);
5294
5295 if OK1 then
5296 Determine_Range
5297 (Type_High_Bound (Ityp), OK1, UL, UU, Assume_Valid);
5298
5299 if OK1 then
5300 -- The maximum value for Length is the biggest
5301 -- possible gap between the values of the bounds.
5302 -- But of course, this value cannot be negative.
5303
5304 Hir := UI_Max (Uint_0, UU - LL + 1);
5305
5306 -- For a constrained array, the minimum value for
5307 -- Length is taken from the actual value of the
5308 -- bounds, since the index will be exactly of this
5309 -- subtype.
5310
5311 if Is_Constrained (Ptyp) then
5312 Lor := UI_Max (Uint_0, UL - LU + 1);
5313
5314 -- For an unconstrained array, the minimum value
5315 -- for length is always zero.
5316
5317 else
5318 Lor := Uint_0;
5319 end if;
5320 end if;
5321 end if;
5322
5323 -- Small optimization: the maximum size in storage units
5324 -- an object can have with GNAT is half of the address
5325 -- space, so we can bound the length of an array declared
5326 -- in Interfaces (or its children) because its component
5327 -- size is at least the storage unit and it is meant to
5328 -- be used to interface actual array objects.
5329
5330 if Is_Array_Type (Ptyp) then
5331 declare
5332 S : constant Entity_Id := Scope (Base_Type (Ptyp));
5333 begin
5334 if Is_RTU (S, Interfaces)
5335 or else (S /= Standard_Standard
5336 and then Is_RTU (Scope (S), Interfaces))
5337 then
5338 Hir := UI_Min (Hir, Half_Address_Space);
5339 end if;
5340 end;
5341 end if;
5342 end;
5343
5344 -- The maximum default alignment is quite low, but GNAT accepts
5345 -- alignment clauses that are fairly large, but not as large as
5346 -- the maximum size of objects, see below.
5347
5348 when Attribute_Alignment =>
5349 Lor := Uint_0;
5350 Hir := Half_Address_Space;
5351 OK1 := True;
5352
5353 -- The attribute should have been folded if a component clause
5354 -- was specified, so we assume there is none.
5355
5356 when Attribute_Bit
5357 | Attribute_First_Bit
5358 =>
5359 Lor := Uint_0;
5360 Hir := UI_From_Int (System_Storage_Unit - 1);
5361 OK1 := True;
5362
5363 -- Likewise about the component clause. Note that Last_Bit
5364 -- yields -1 for a field of size 0 if First_Bit is 0.
5365
5366 when Attribute_Last_Bit =>
5367 Lor := Uint_Minus_1;
5368 Hir := Hi;
5369 OK1 := True;
5370
5371 -- Likewise about the component clause for Position. The
5372 -- maximum size in storage units that an object can have
5373 -- with GNAT is half of the address space.
5374
5375 when Attribute_Max_Size_In_Storage_Elements
5376 | Attribute_Position
5377 =>
5378 Lor := Uint_0;
5379 Hir := Half_Address_Space;
5380 OK1 := True;
5381
5382 -- These attributes yield a nonnegative value (we do not set
5383 -- the maximum value because it is too large to be useful).
5384
5385 when Attribute_Bit_Position
5386 | Attribute_Component_Size
5387 | Attribute_Object_Size
5388 | Attribute_Size
5389 | Attribute_Value_Size
5390 =>
5391 Lor := Uint_0;
5392 Hir := Hi;
5393 OK1 := True;
5394
5395 -- The maximum size is the sum of twice the size of the largest
5396 -- integer for every dimension, rounded up to the next multiple
5397 -- of the maximum alignment, but we add instead of rounding.
5398
5399 when Attribute_Descriptor_Size =>
5400 declare
5401 Max_Align : constant Pos :=
5402 Maximum_Alignment * System_Storage_Unit;
5403 Max_Size : constant Uint :=
5404 2 * Esize (Universal_Integer);
5405 Ndims : constant Pos :=
5406 Number_Dimensions (Etype (Prefix (N)));
5407 begin
5408 Lor := Uint_0;
5409 Hir := Max_Size * Ndims + Max_Align;
5410 OK1 := True;
5411 end;
5412
5413 -- No special handling for other attributes for now
5414
5415 when others =>
5416 OK1 := False;
5417
5418 end case;
5419
5420 when N_Type_Conversion =>
5421 -- For a type conversion, we can try to refine the range using the
5422 -- converted value.
5423
5424 Determine_Range_To_Discrete
5425 (Expression (N), OK1, Lor, Hir, Conversion_OK (N), Assume_Valid);
5426
5427 -- Nothing special to do for all other expression kinds
5428
5429 when others =>
5430 OK1 := False;
5431 Lor := No_Uint;
5432 Hir := No_Uint;
5433 end case;
5434
5435 -- At this stage, if OK1 is true, then we know that the actual result of
5436 -- the computed expression is in the range Lor .. Hir. We can use this
5437 -- to restrict the possible range of results.
5438
5439 if OK1 then
5440
5441 -- If the refined value of the low bound is greater than the type
5442 -- low bound, then reset it to the more restrictive value. However,
5443 -- we do NOT do this for the case of a modular type where the
5444 -- possible upper bound on the value is above the base type high
5445 -- bound, because that means the result could wrap.
5446
5447 if Lor > Lo
5448 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
5449 then
5450 Lo := Lor;
5451 end if;
5452
5453 -- Similarly, if the refined value of the high bound is less than the
5454 -- value so far, then reset it to the more restrictive value. Again,
5455 -- we do not do this if the refined low bound is negative for a
5456 -- modular type, since this would wrap.
5457
5458 if Hir < Hi
5459 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
5460 then
5461 Hi := Hir;
5462 end if;
5463 end if;
5464
5465 -- Set cache entry for future call and we are all done
5466
5467 Determine_Range_Cache_N (Cindex) := N;
5468 Determine_Range_Cache_O (Cindex) := Original_Node (N);
5469 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5470 Determine_Range_Cache_Lo (Cindex) := Lo;
5471 Determine_Range_Cache_Hi (Cindex) := Hi;
5472 return;
5473
5474 -- If any exception occurs, it means that we have some bug in the compiler,
5475 -- possibly triggered by a previous error, or by some unforeseen peculiar
5476 -- occurrence. However, this is only an optimization attempt, so there is
5477 -- really no point in crashing the compiler. Instead we just decide, too
5478 -- bad, we can't figure out a range in this case after all.
5479
5480 exception
5481 when others =>
5482
5483 -- Debug flag K disables this behavior (useful for debugging)
5484
5485 if Debug_Flag_K then
5486 raise;
5487 else
5488 OK := False;
5489 Lo := No_Uint;
5490 Hi := No_Uint;
5491 return;
5492 end if;
5493 end Determine_Range;
5494
5495 -----------------------
5496 -- Determine_Range_R --
5497 -----------------------
5498
5499 procedure Determine_Range_R
5500 (N : Node_Id;
5501 OK : out Boolean;
5502 Lo : out Ureal;
5503 Hi : out Ureal;
5504 Assume_Valid : Boolean := False)
5505 is
5506 Typ : Entity_Id := Etype (N);
5507 -- Type to use, may get reset to base type for possibly invalid entity
5508
5509 Lo_Left : Ureal;
5510 Hi_Left : Ureal;
5511 -- Lo and Hi bounds of left operand
5512
5513 Lo_Right : Ureal := No_Ureal;
5514 Hi_Right : Ureal := No_Ureal;
5515 -- Lo and Hi bounds of right (or only) operand
5516
5517 Bound : Node_Id;
5518 -- Temp variable used to hold a bound node
5519
5520 Hbound : Ureal;
5521 -- High bound of base type of expression
5522
5523 Lor : Ureal;
5524 Hir : Ureal;
5525 -- Refined values for low and high bounds, after tightening
5526
5527 OK1 : Boolean;
5528 -- Used in lower level calls to indicate if call succeeded
5529
5530 Cindex : Cache_Index;
5531 -- Used to search cache
5532
5533 Btyp : Entity_Id;
5534 -- Base type
5535
5536 function OK_Operands return Boolean;
5537 -- Used for binary operators. Determines the ranges of the left and
5538 -- right operands, and if they are both OK, returns True, and puts
5539 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
5540
5541 function Round_Machine (B : Ureal) return Ureal;
5542 -- B is a real bound. Round it using mode Round_Even.
5543
5544 -----------------
5545 -- OK_Operands --
5546 -----------------
5547
5548 function OK_Operands return Boolean is
5549 begin
5550 Determine_Range_R
5551 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
5552
5553 if not OK1 then
5554 return False;
5555 end if;
5556
5557 Determine_Range_R
5558 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5559 return OK1;
5560 end OK_Operands;
5561
5562 -------------------
5563 -- Round_Machine --
5564 -------------------
5565
5566 function Round_Machine (B : Ureal) return Ureal is
5567 begin
5568 return Machine (Typ, B, Round_Even, N);
5569 end Round_Machine;
5570
5571 -- Start of processing for Determine_Range_R
5572
5573 begin
5574 -- Prevent junk warnings by initializing range variables
5575
5576 Lo := No_Ureal;
5577 Hi := No_Ureal;
5578 Lor := No_Ureal;
5579 Hir := No_Ureal;
5580
5581 -- For temporary constants internally generated to remove side effects
5582 -- we must use the corresponding expression to determine the range of
5583 -- the expression. But note that the expander can also generate
5584 -- constants in other cases, including deferred constants.
5585
5586 if Is_Entity_Name (N)
5587 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
5588 and then Ekind (Entity (N)) = E_Constant
5589 and then Is_Internal_Name (Chars (Entity (N)))
5590 then
5591 if Present (Expression (Parent (Entity (N)))) then
5592 Determine_Range_R
5593 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
5594
5595 elsif Present (Full_View (Entity (N))) then
5596 Determine_Range_R
5597 (Expression (Parent (Full_View (Entity (N)))),
5598 OK, Lo, Hi, Assume_Valid);
5599
5600 else
5601 OK := False;
5602 end if;
5603
5604 return;
5605 end if;
5606
5607 -- If type is not defined, we can't determine its range
5608
5609 if No (Typ)
5610
5611 -- We don't deal with anything except IEEE floating-point types
5612
5613 or else not Is_Floating_Point_Type (Typ)
5614 or else Float_Rep (Typ) /= IEEE_Binary
5615
5616 -- Ignore type for which an error has been posted, since range in
5617 -- this case may well be a bogosity deriving from the error. Also
5618 -- ignore if error posted on the reference node.
5619
5620 or else Error_Posted (N) or else Error_Posted (Typ)
5621 then
5622 OK := False;
5623 return;
5624 end if;
5625
5626 -- For all other cases, we can determine the range
5627
5628 OK := True;
5629
5630 -- If value is compile time known, then the possible range is the one
5631 -- value that we know this expression definitely has.
5632
5633 if Compile_Time_Known_Value (N) then
5634 Lo := Expr_Value_R (N);
5635 Hi := Lo;
5636 return;
5637 end if;
5638
5639 -- Return if already in the cache
5640
5641 Cindex := Cache_Index (N mod Cache_Size);
5642
5643 if Determine_Range_Cache_N (Cindex) = N
5644 and then
5645 Determine_Range_Cache_O (Cindex) = Original_Node (N)
5646 and then
5647 Determine_Range_Cache_V (Cindex) = Assume_Valid
5648 then
5649 Lo := Determine_Range_Cache_Lo_R (Cindex);
5650 Hi := Determine_Range_Cache_Hi_R (Cindex);
5651 return;
5652 end if;
5653
5654 -- Otherwise, start by finding the bounds of the type of the expression,
5655 -- the value cannot be outside this range (if it is, then we have an
5656 -- overflow situation, which is a separate check, we are talking here
5657 -- only about the expression value).
5658
5659 -- First a check, never try to find the bounds of a generic type, since
5660 -- these bounds are always junk values, and it is only valid to look at
5661 -- the bounds in an instance.
5662
5663 if Is_Generic_Type (Typ) then
5664 OK := False;
5665 return;
5666 end if;
5667
5668 -- First step, change to use base type unless we know the value is valid
5669
5670 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
5671 or else Assume_No_Invalid_Values
5672 or else Assume_Valid
5673 then
5674 null;
5675 else
5676 Typ := Underlying_Type (Base_Type (Typ));
5677 end if;
5678
5679 -- Retrieve the base type. Handle the case where the base type is a
5680 -- private type.
5681
5682 Btyp := Base_Type (Typ);
5683
5684 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
5685 Btyp := Full_View (Btyp);
5686 end if;
5687
5688 -- We use the actual bound unless it is dynamic, in which case use the
5689 -- corresponding base type bound if possible. If we can't get a bound
5690 -- then we figure we can't determine the range (a peculiar case, that
5691 -- perhaps cannot happen, but there is no point in bombing in this
5692 -- optimization circuit).
5693
5694 -- First the low bound
5695
5696 Bound := Type_Low_Bound (Typ);
5697
5698 if Compile_Time_Known_Value (Bound) then
5699 Lo := Expr_Value_R (Bound);
5700
5701 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
5702 Lo := Expr_Value_R (Type_Low_Bound (Btyp));
5703
5704 else
5705 OK := False;
5706 return;
5707 end if;
5708
5709 -- Now the high bound
5710
5711 Bound := Type_High_Bound (Typ);
5712
5713 -- We need the high bound of the base type later on, and this should
5714 -- always be compile time known. Again, it is not clear that this
5715 -- can ever be false, but no point in bombing.
5716
5717 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
5718 Hbound := Expr_Value_R (Type_High_Bound (Btyp));
5719 Hi := Hbound;
5720
5721 else
5722 OK := False;
5723 return;
5724 end if;
5725
5726 -- If we have a static subtype, then that may have a tighter bound so
5727 -- use the upper bound of the subtype instead in this case.
5728
5729 if Compile_Time_Known_Value (Bound) then
5730 Hi := Expr_Value_R (Bound);
5731 end if;
5732
5733 -- We may be able to refine this value in certain situations. If any
5734 -- refinement is possible, then Lor and Hir are set to possibly tighter
5735 -- bounds, and OK1 is set to True.
5736
5737 case Nkind (N) is
5738
5739 -- For unary plus, result is limited by range of operand
5740
5741 when N_Op_Plus =>
5742 Determine_Range_R
5743 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
5744
5745 -- For unary minus, determine range of operand, and negate it
5746
5747 when N_Op_Minus =>
5748 Determine_Range_R
5749 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5750
5751 if OK1 then
5752 Lor := -Hi_Right;
5753 Hir := -Lo_Right;
5754 end if;
5755
5756 -- For binary addition, get range of each operand and do the
5757 -- addition to get the result range.
5758
5759 when N_Op_Add =>
5760 if OK_Operands then
5761 Lor := Round_Machine (Lo_Left + Lo_Right);
5762 Hir := Round_Machine (Hi_Left + Hi_Right);
5763 end if;
5764
5765 -- For binary subtraction, get range of each operand and do the worst
5766 -- case subtraction to get the result range.
5767
5768 when N_Op_Subtract =>
5769 if OK_Operands then
5770 Lor := Round_Machine (Lo_Left - Hi_Right);
5771 Hir := Round_Machine (Hi_Left - Lo_Right);
5772 end if;
5773
5774 -- For multiplication, get range of each operand and do the
5775 -- four multiplications to get the result range.
5776
5777 when N_Op_Multiply =>
5778 if OK_Operands then
5779 declare
5780 M1 : constant Ureal := Round_Machine (Lo_Left * Lo_Right);
5781 M2 : constant Ureal := Round_Machine (Lo_Left * Hi_Right);
5782 M3 : constant Ureal := Round_Machine (Hi_Left * Lo_Right);
5783 M4 : constant Ureal := Round_Machine (Hi_Left * Hi_Right);
5784
5785 begin
5786 Lor := UR_Min (UR_Min (M1, M2), UR_Min (M3, M4));
5787 Hir := UR_Max (UR_Max (M1, M2), UR_Max (M3, M4));
5788 end;
5789 end if;
5790
5791 -- For division, consider separately the cases where the right
5792 -- operand is positive or negative. Otherwise, the right operand
5793 -- can be arbitrarily close to zero, so the result is likely to
5794 -- be unbounded in one direction, do not attempt to compute it.
5795
5796 when N_Op_Divide =>
5797 if OK_Operands then
5798
5799 -- Right operand is positive
5800
5801 if Lo_Right > Ureal_0 then
5802
5803 -- If the low bound of the left operand is negative, obtain
5804 -- the overall low bound by dividing it by the smallest
5805 -- value of the right operand, and otherwise by the largest
5806 -- value of the right operand.
5807
5808 if Lo_Left < Ureal_0 then
5809 Lor := Round_Machine (Lo_Left / Lo_Right);
5810 else
5811 Lor := Round_Machine (Lo_Left / Hi_Right);
5812 end if;
5813
5814 -- If the high bound of the left operand is negative, obtain
5815 -- the overall high bound by dividing it by the largest
5816 -- value of the right operand, and otherwise by the
5817 -- smallest value of the right operand.
5818
5819 if Hi_Left < Ureal_0 then
5820 Hir := Round_Machine (Hi_Left / Hi_Right);
5821 else
5822 Hir := Round_Machine (Hi_Left / Lo_Right);
5823 end if;
5824
5825 -- Right operand is negative
5826
5827 elsif Hi_Right < Ureal_0 then
5828
5829 -- If the low bound of the left operand is negative, obtain
5830 -- the overall low bound by dividing it by the largest
5831 -- value of the right operand, and otherwise by the smallest
5832 -- value of the right operand.
5833
5834 if Lo_Left < Ureal_0 then
5835 Lor := Round_Machine (Lo_Left / Hi_Right);
5836 else
5837 Lor := Round_Machine (Lo_Left / Lo_Right);
5838 end if;
5839
5840 -- If the high bound of the left operand is negative, obtain
5841 -- the overall high bound by dividing it by the smallest
5842 -- value of the right operand, and otherwise by the
5843 -- largest value of the right operand.
5844
5845 if Hi_Left < Ureal_0 then
5846 Hir := Round_Machine (Hi_Left / Lo_Right);
5847 else
5848 Hir := Round_Machine (Hi_Left / Hi_Right);
5849 end if;
5850
5851 else
5852 OK1 := False;
5853 end if;
5854 end if;
5855
5856 when N_Type_Conversion =>
5857
5858 -- For type conversion from one floating-point type to another, we
5859 -- can refine the range using the converted value.
5860
5861 if Is_Floating_Point_Type (Etype (Expression (N))) then
5862 Determine_Range_R (Expression (N), OK1, Lor, Hir, Assume_Valid);
5863
5864 -- When converting an integer to a floating-point type, determine
5865 -- the range in integer first, and then convert the bounds.
5866
5867 elsif Is_Discrete_Type (Etype (Expression (N))) then
5868 declare
5869 Hir_Int : Uint;
5870 Lor_Int : Uint;
5871
5872 begin
5873 Determine_Range
5874 (Expression (N), OK1, Lor_Int, Hir_Int, Assume_Valid);
5875
5876 if OK1 then
5877 Lor := Round_Machine (UR_From_Uint (Lor_Int));
5878 Hir := Round_Machine (UR_From_Uint (Hir_Int));
5879 end if;
5880 end;
5881
5882 else
5883 OK1 := False;
5884 end if;
5885
5886 -- Nothing special to do for all other expression kinds
5887
5888 when others =>
5889 OK1 := False;
5890 Lor := No_Ureal;
5891 Hir := No_Ureal;
5892 end case;
5893
5894 -- At this stage, if OK1 is true, then we know that the actual result of
5895 -- the computed expression is in the range Lor .. Hir. We can use this
5896 -- to restrict the possible range of results.
5897
5898 if OK1 then
5899
5900 -- If the refined value of the low bound is greater than the type
5901 -- low bound, then reset it to the more restrictive value.
5902
5903 if Lor > Lo then
5904 Lo := Lor;
5905 end if;
5906
5907 -- Similarly, if the refined value of the high bound is less than the
5908 -- value so far, then reset it to the more restrictive value.
5909
5910 if Hir < Hi then
5911 Hi := Hir;
5912 end if;
5913 end if;
5914
5915 -- Set cache entry for future call and we are all done
5916
5917 Determine_Range_Cache_N (Cindex) := N;
5918 Determine_Range_Cache_O (Cindex) := Original_Node (N);
5919 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5920 Determine_Range_Cache_Lo_R (Cindex) := Lo;
5921 Determine_Range_Cache_Hi_R (Cindex) := Hi;
5922 return;
5923
5924 -- If any exception occurs, it means that we have some bug in the compiler,
5925 -- possibly triggered by a previous error, or by some unforeseen peculiar
5926 -- occurrence. However, this is only an optimization attempt, so there is
5927 -- really no point in crashing the compiler. Instead we just decide, too
5928 -- bad, we can't figure out a range in this case after all.
5929
5930 exception
5931 when others =>
5932
5933 -- Debug flag K disables this behavior (useful for debugging)
5934
5935 if Debug_Flag_K then
5936 raise;
5937 else
5938 OK := False;
5939 Lo := No_Ureal;
5940 Hi := No_Ureal;
5941 return;
5942 end if;
5943 end Determine_Range_R;
5944
5945 ---------------------------------
5946 -- Determine_Range_To_Discrete --
5947 ---------------------------------
5948
5949 procedure Determine_Range_To_Discrete
5950 (N : Node_Id;
5951 OK : out Boolean;
5952 Lo : out Uint;
5953 Hi : out Uint;
5954 Fixed_Int : Boolean := False;
5955 Assume_Valid : Boolean := False)
5956 is
5957 Typ : constant Entity_Id := Etype (N);
5958
5959 begin
5960 -- For a discrete type, simply defer to Determine_Range
5961
5962 if Is_Discrete_Type (Typ) then
5963 Determine_Range (N, OK, Lo, Hi, Assume_Valid);
5964
5965 -- For a fixed point type treated as an integer, we can determine the
5966 -- range using the Corresponding_Integer_Value of the bounds of the
5967 -- type or base type. This is done by the calls to Expr_Value below.
5968
5969 elsif Is_Fixed_Point_Type (Typ) and then Fixed_Int then
5970 declare
5971 Btyp, Ftyp : Entity_Id;
5972 Bound : Node_Id;
5973
5974 begin
5975 if Assume_Valid then
5976 Ftyp := Typ;
5977 else
5978 Ftyp := Underlying_Type (Base_Type (Typ));
5979 end if;
5980
5981 Btyp := Base_Type (Ftyp);
5982
5983 -- First the low bound
5984
5985 Bound := Type_Low_Bound (Ftyp);
5986
5987 if Compile_Time_Known_Value (Bound) then
5988 Lo := Expr_Value (Bound);
5989 else
5990 Lo := Expr_Value (Type_Low_Bound (Btyp));
5991 end if;
5992
5993 -- Then the high bound
5994
5995 Bound := Type_High_Bound (Ftyp);
5996
5997 if Compile_Time_Known_Value (Bound) then
5998 Hi := Expr_Value (Bound);
5999 else
6000 Hi := Expr_Value (Type_High_Bound (Btyp));
6001 end if;
6002
6003 OK := True;
6004 end;
6005
6006 -- For a floating-point type, we can determine the range in real first,
6007 -- and then convert the bounds using UR_To_Uint, which correctly rounds
6008 -- away from zero when half way between two integers, as required by
6009 -- normal Ada 95 rounding semantics. But this is only possible because
6010 -- GNATprove's analysis rules out the possibility of a NaN or infinite.
6011
6012 elsif GNATprove_Mode and then Is_Floating_Point_Type (Typ) then
6013 declare
6014 Lo_Real, Hi_Real : Ureal;
6015
6016 begin
6017 Determine_Range_R (N, OK, Lo_Real, Hi_Real, Assume_Valid);
6018
6019 if OK then
6020 Lo := UR_To_Uint (Lo_Real);
6021 Hi := UR_To_Uint (Hi_Real);
6022 else
6023 Lo := No_Uint;
6024 Hi := No_Uint;
6025 end if;
6026 end;
6027
6028 else
6029 Lo := No_Uint;
6030 Hi := No_Uint;
6031 OK := False;
6032 end if;
6033 end Determine_Range_To_Discrete;
6034
6035 ------------------------------------
6036 -- Discriminant_Checks_Suppressed --
6037 ------------------------------------
6038
6039 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
6040 begin
6041 if Present (E) then
6042 if Is_Unchecked_Union (E) then
6043 return True;
6044 elsif Checks_May_Be_Suppressed (E) then
6045 return Is_Check_Suppressed (E, Discriminant_Check);
6046 end if;
6047 end if;
6048
6049 return Scope_Suppress.Suppress (Discriminant_Check);
6050 end Discriminant_Checks_Suppressed;
6051
6052 --------------------------------
6053 -- Division_Checks_Suppressed --
6054 --------------------------------
6055
6056 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
6057 begin
6058 if Present (E) and then Checks_May_Be_Suppressed (E) then
6059 return Is_Check_Suppressed (E, Division_Check);
6060 else
6061 return Scope_Suppress.Suppress (Division_Check);
6062 end if;
6063 end Division_Checks_Suppressed;
6064
6065 --------------------------------------
6066 -- Duplicated_Tag_Checks_Suppressed --
6067 --------------------------------------
6068
6069 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
6070 begin
6071 if Present (E) and then Checks_May_Be_Suppressed (E) then
6072 return Is_Check_Suppressed (E, Duplicated_Tag_Check);
6073 else
6074 return Scope_Suppress.Suppress (Duplicated_Tag_Check);
6075 end if;
6076 end Duplicated_Tag_Checks_Suppressed;
6077
6078 -----------------------------------
6079 -- Elaboration_Checks_Suppressed --
6080 -----------------------------------
6081
6082 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
6083 begin
6084 -- The complication in this routine is that if we are in the dynamic
6085 -- model of elaboration, we also check All_Checks, since All_Checks
6086 -- does not set Elaboration_Check explicitly.
6087
6088 if Present (E) then
6089 if Kill_Elaboration_Checks (E) then
6090 return True;
6091
6092 elsif Checks_May_Be_Suppressed (E) then
6093 if Is_Check_Suppressed (E, Elaboration_Check) then
6094 return True;
6095
6096 elsif Dynamic_Elaboration_Checks then
6097 return Is_Check_Suppressed (E, All_Checks);
6098
6099 else
6100 return False;
6101 end if;
6102 end if;
6103 end if;
6104
6105 if Scope_Suppress.Suppress (Elaboration_Check) then
6106 return True;
6107
6108 elsif Dynamic_Elaboration_Checks then
6109 return Scope_Suppress.Suppress (All_Checks);
6110
6111 else
6112 return False;
6113 end if;
6114 end Elaboration_Checks_Suppressed;
6115
6116 ---------------------------
6117 -- Enable_Overflow_Check --
6118 ---------------------------
6119
6120 procedure Enable_Overflow_Check (N : Node_Id) is
6121 Typ : constant Entity_Id := Base_Type (Etype (N));
6122 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
6123 Chk : Nat;
6124 OK : Boolean;
6125 Ent : Entity_Id;
6126 Ofs : Uint;
6127 Lo : Uint;
6128 Hi : Uint;
6129
6130 Do_Ovflow_Check : Boolean;
6131
6132 begin
6133 if Debug_Flag_CC then
6134 w ("Enable_Overflow_Check for node ", Int (N));
6135 Write_Str (" Source location = ");
6136 wl (Sloc (N));
6137 pg (Union_Id (N));
6138 end if;
6139
6140 -- No check if overflow checks suppressed for type of node
6141
6142 if Overflow_Checks_Suppressed (Etype (N)) then
6143 return;
6144
6145 -- Nothing to do for unsigned integer types, which do not overflow
6146
6147 elsif Is_Modular_Integer_Type (Typ) then
6148 return;
6149 end if;
6150
6151 -- This is the point at which processing for STRICT mode diverges
6152 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
6153 -- probably more extreme that it needs to be, but what is going on here
6154 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
6155 -- to leave the processing for STRICT mode untouched. There were
6156 -- two reasons for this. First it avoided any incompatible change of
6157 -- behavior. Second, it guaranteed that STRICT mode continued to be
6158 -- legacy reliable.
6159
6160 -- The big difference is that in STRICT mode there is a fair amount of
6161 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
6162 -- know that no check is needed. We skip all that in the two new modes,
6163 -- since really overflow checking happens over a whole subtree, and we
6164 -- do the corresponding optimizations later on when applying the checks.
6165
6166 if Mode in Minimized_Or_Eliminated then
6167 if not (Overflow_Checks_Suppressed (Etype (N)))
6168 and then not (Is_Entity_Name (N)
6169 and then Overflow_Checks_Suppressed (Entity (N)))
6170 then
6171 Activate_Overflow_Check (N);
6172 end if;
6173
6174 if Debug_Flag_CC then
6175 w ("Minimized/Eliminated mode");
6176 end if;
6177
6178 return;
6179 end if;
6180
6181 -- Remainder of processing is for STRICT case, and is unchanged from
6182 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
6183
6184 -- Nothing to do if the range of the result is known OK. We skip this
6185 -- for conversions, since the caller already did the check, and in any
6186 -- case the condition for deleting the check for a type conversion is
6187 -- different.
6188
6189 if Nkind (N) /= N_Type_Conversion then
6190 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
6191
6192 -- Note in the test below that we assume that the range is not OK
6193 -- if a bound of the range is equal to that of the type. That's not
6194 -- quite accurate but we do this for the following reasons:
6195
6196 -- a) The way that Determine_Range works, it will typically report
6197 -- the bounds of the value as being equal to the bounds of the
6198 -- type, because it either can't tell anything more precise, or
6199 -- does not think it is worth the effort to be more precise.
6200
6201 -- b) It is very unusual to have a situation in which this would
6202 -- generate an unnecessary overflow check (an example would be
6203 -- a subtype with a range 0 .. Integer'Last - 1 to which the
6204 -- literal value one is added).
6205
6206 -- c) The alternative is a lot of special casing in this routine
6207 -- which would partially duplicate Determine_Range processing.
6208
6209 if OK then
6210 Do_Ovflow_Check := True;
6211
6212 -- Note that the following checks are quite deliberately > and <
6213 -- rather than >= and <= as explained above.
6214
6215 if Lo > Expr_Value (Type_Low_Bound (Typ))
6216 and then
6217 Hi < Expr_Value (Type_High_Bound (Typ))
6218 then
6219 Do_Ovflow_Check := False;
6220
6221 -- Despite the comments above, it is worth dealing specially with
6222 -- division. The only case where integer division can overflow is
6223 -- (largest negative number) / (-1). So we will do an extra range
6224 -- analysis to see if this is possible.
6225
6226 elsif Nkind (N) = N_Op_Divide then
6227 Determine_Range
6228 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
6229
6230 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
6231 Do_Ovflow_Check := False;
6232
6233 else
6234 Determine_Range
6235 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
6236
6237 if OK and then (Lo > Uint_Minus_1
6238 or else
6239 Hi < Uint_Minus_1)
6240 then
6241 Do_Ovflow_Check := False;
6242 end if;
6243 end if;
6244
6245 -- Likewise for Abs/Minus, the only case where the operation can
6246 -- overflow is when the operand is the largest negative number.
6247
6248 elsif Nkind (N) in N_Op_Abs | N_Op_Minus then
6249 Determine_Range
6250 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
6251
6252 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
6253 Do_Ovflow_Check := False;
6254 end if;
6255 end if;
6256
6257 -- If no overflow check required, we are done
6258
6259 if not Do_Ovflow_Check then
6260 if Debug_Flag_CC then
6261 w ("No overflow check required");
6262 end if;
6263
6264 return;
6265 end if;
6266 end if;
6267 end if;
6268
6269 -- If not in optimizing mode, set flag and we are done. We are also done
6270 -- (and just set the flag) if the type is not a discrete type, since it
6271 -- is not worth the effort to eliminate checks for other than discrete
6272 -- types. In addition, we take this same path if we have stored the
6273 -- maximum number of checks possible already (a very unlikely situation,
6274 -- but we do not want to blow up).
6275
6276 if Optimization_Level = 0
6277 or else not Is_Discrete_Type (Etype (N))
6278 or else Num_Saved_Checks = Saved_Checks'Last
6279 then
6280 Activate_Overflow_Check (N);
6281
6282 if Debug_Flag_CC then
6283 w ("Optimization off");
6284 end if;
6285
6286 return;
6287 end if;
6288
6289 -- Otherwise evaluate and check the expression
6290
6291 Find_Check
6292 (Expr => N,
6293 Check_Type => 'O',
6294 Target_Type => Empty,
6295 Entry_OK => OK,
6296 Check_Num => Chk,
6297 Ent => Ent,
6298 Ofs => Ofs);
6299
6300 if Debug_Flag_CC then
6301 w ("Called Find_Check");
6302 w (" OK = ", OK);
6303
6304 if OK then
6305 w (" Check_Num = ", Chk);
6306 w (" Ent = ", Int (Ent));
6307 Write_Str (" Ofs = ");
6308 pid (Ofs);
6309 end if;
6310 end if;
6311
6312 -- If check is not of form to optimize, then set flag and we are done
6313
6314 if not OK then
6315 Activate_Overflow_Check (N);
6316 return;
6317 end if;
6318
6319 -- If check is already performed, then return without setting flag
6320
6321 if Chk /= 0 then
6322 if Debug_Flag_CC then
6323 w ("Check suppressed!");
6324 end if;
6325
6326 return;
6327 end if;
6328
6329 -- Here we will make a new entry for the new check
6330
6331 Activate_Overflow_Check (N);
6332 Num_Saved_Checks := Num_Saved_Checks + 1;
6333 Saved_Checks (Num_Saved_Checks) :=
6334 (Killed => False,
6335 Entity => Ent,
6336 Offset => Ofs,
6337 Check_Type => 'O',
6338 Target_Type => Empty);
6339
6340 if Debug_Flag_CC then
6341 w ("Make new entry, check number = ", Num_Saved_Checks);
6342 w (" Entity = ", Int (Ent));
6343 Write_Str (" Offset = ");
6344 pid (Ofs);
6345 w (" Check_Type = O");
6346 w (" Target_Type = Empty");
6347 end if;
6348
6349 -- If we get an exception, then something went wrong, probably because of
6350 -- an error in the structure of the tree due to an incorrect program. Or
6351 -- it may be a bug in the optimization circuit. In either case the safest
6352 -- thing is simply to set the check flag unconditionally.
6353
6354 exception
6355 when others =>
6356 Activate_Overflow_Check (N);
6357
6358 if Debug_Flag_CC then
6359 w (" exception occurred, overflow flag set");
6360 end if;
6361
6362 return;
6363 end Enable_Overflow_Check;
6364
6365 ------------------------
6366 -- Enable_Range_Check --
6367 ------------------------
6368
6369 procedure Enable_Range_Check (N : Node_Id) is
6370 Chk : Nat;
6371 OK : Boolean;
6372 Ent : Entity_Id;
6373 Ofs : Uint;
6374 Ttyp : Entity_Id;
6375 P : Node_Id;
6376
6377 begin
6378 -- Return if unchecked type conversion with range check killed. In this
6379 -- case we never set the flag (that's what Kill_Range_Check is about).
6380
6381 if Nkind (N) = N_Unchecked_Type_Conversion
6382 and then Kill_Range_Check (N)
6383 then
6384 return;
6385 end if;
6386
6387 -- Do not set range check flag if parent is assignment statement or
6388 -- object declaration with Suppress_Assignment_Checks flag set
6389
6390 if Nkind (Parent (N)) in N_Assignment_Statement | N_Object_Declaration
6391 and then Suppress_Assignment_Checks (Parent (N))
6392 then
6393 return;
6394 end if;
6395
6396 -- Check for various cases where we should suppress the range check
6397
6398 -- No check if range checks suppressed for type of node
6399
6400 if Present (Etype (N)) and then Range_Checks_Suppressed (Etype (N)) then
6401 return;
6402
6403 -- No check if node is an entity name, and range checks are suppressed
6404 -- for this entity, or for the type of this entity.
6405
6406 elsif Is_Entity_Name (N)
6407 and then (Range_Checks_Suppressed (Entity (N))
6408 or else Range_Checks_Suppressed (Etype (Entity (N))))
6409 then
6410 return;
6411
6412 -- No checks if index of array, and index checks are suppressed for
6413 -- the array object or the type of the array.
6414
6415 elsif Nkind (Parent (N)) = N_Indexed_Component then
6416 declare
6417 Pref : constant Node_Id := Prefix (Parent (N));
6418 begin
6419 if Is_Entity_Name (Pref)
6420 and then Index_Checks_Suppressed (Entity (Pref))
6421 then
6422 return;
6423 elsif Index_Checks_Suppressed (Etype (Pref)) then
6424 return;
6425 end if;
6426 end;
6427 end if;
6428
6429 -- Debug trace output
6430
6431 if Debug_Flag_CC then
6432 w ("Enable_Range_Check for node ", Int (N));
6433 Write_Str (" Source location = ");
6434 wl (Sloc (N));
6435 pg (Union_Id (N));
6436 end if;
6437
6438 -- If not in optimizing mode, set flag and we are done. We are also done
6439 -- (and just set the flag) if the type is not a discrete type, since it
6440 -- is not worth the effort to eliminate checks for other than discrete
6441 -- types. In addition, we take this same path if we have stored the
6442 -- maximum number of checks possible already (a very unlikely situation,
6443 -- but we do not want to blow up).
6444
6445 if Optimization_Level = 0
6446 or else No (Etype (N))
6447 or else not Is_Discrete_Type (Etype (N))
6448 or else Num_Saved_Checks = Saved_Checks'Last
6449 then
6450 Activate_Range_Check (N);
6451
6452 if Debug_Flag_CC then
6453 w ("Optimization off");
6454 end if;
6455
6456 return;
6457 end if;
6458
6459 -- Otherwise find out the target type
6460
6461 P := Parent (N);
6462
6463 -- For assignment, use left side subtype
6464
6465 if Nkind (P) = N_Assignment_Statement
6466 and then Expression (P) = N
6467 then
6468 Ttyp := Etype (Name (P));
6469
6470 -- For indexed component, use subscript subtype
6471
6472 elsif Nkind (P) = N_Indexed_Component then
6473 declare
6474 Atyp : Entity_Id;
6475 Indx : Node_Id;
6476 Subs : Node_Id;
6477
6478 begin
6479 Atyp := Etype (Prefix (P));
6480
6481 if Is_Access_Type (Atyp) then
6482 Atyp := Designated_Type (Atyp);
6483
6484 -- If the prefix is an access to an unconstrained array,
6485 -- perform check unconditionally: it depends on the bounds of
6486 -- an object and we cannot currently recognize whether the test
6487 -- may be redundant.
6488
6489 if not Is_Constrained (Atyp) then
6490 Activate_Range_Check (N);
6491 return;
6492 end if;
6493
6494 -- Ditto if prefix is simply an unconstrained array. We used
6495 -- to think this case was OK, if the prefix was not an explicit
6496 -- dereference, but we have now seen a case where this is not
6497 -- true, so it is safer to just suppress the optimization in this
6498 -- case. The back end is getting better at eliminating redundant
6499 -- checks in any case, so the loss won't be important.
6500
6501 elsif Is_Array_Type (Atyp)
6502 and then not Is_Constrained (Atyp)
6503 then
6504 Activate_Range_Check (N);
6505 return;
6506 end if;
6507
6508 Indx := First_Index (Atyp);
6509 Subs := First (Expressions (P));
6510 loop
6511 if Subs = N then
6512 Ttyp := Etype (Indx);
6513 exit;
6514 end if;
6515
6516 Next_Index (Indx);
6517 Next (Subs);
6518 end loop;
6519 end;
6520
6521 -- For now, ignore all other cases, they are not so interesting
6522
6523 else
6524 if Debug_Flag_CC then
6525 w (" target type not found, flag set");
6526 end if;
6527
6528 Activate_Range_Check (N);
6529 return;
6530 end if;
6531
6532 -- Evaluate and check the expression
6533
6534 Find_Check
6535 (Expr => N,
6536 Check_Type => 'R',
6537 Target_Type => Ttyp,
6538 Entry_OK => OK,
6539 Check_Num => Chk,
6540 Ent => Ent,
6541 Ofs => Ofs);
6542
6543 if Debug_Flag_CC then
6544 w ("Called Find_Check");
6545 w ("Target_Typ = ", Int (Ttyp));
6546 w (" OK = ", OK);
6547
6548 if OK then
6549 w (" Check_Num = ", Chk);
6550 w (" Ent = ", Int (Ent));
6551 Write_Str (" Ofs = ");
6552 pid (Ofs);
6553 end if;
6554 end if;
6555
6556 -- If check is not of form to optimize, then set flag and we are done
6557
6558 if not OK then
6559 if Debug_Flag_CC then
6560 w (" expression not of optimizable type, flag set");
6561 end if;
6562
6563 Activate_Range_Check (N);
6564 return;
6565 end if;
6566
6567 -- If check is already performed, then return without setting flag
6568
6569 if Chk /= 0 then
6570 if Debug_Flag_CC then
6571 w ("Check suppressed!");
6572 end if;
6573
6574 return;
6575 end if;
6576
6577 -- Here we will make a new entry for the new check
6578
6579 Activate_Range_Check (N);
6580 Num_Saved_Checks := Num_Saved_Checks + 1;
6581 Saved_Checks (Num_Saved_Checks) :=
6582 (Killed => False,
6583 Entity => Ent,
6584 Offset => Ofs,
6585 Check_Type => 'R',
6586 Target_Type => Ttyp);
6587
6588 if Debug_Flag_CC then
6589 w ("Make new entry, check number = ", Num_Saved_Checks);
6590 w (" Entity = ", Int (Ent));
6591 Write_Str (" Offset = ");
6592 pid (Ofs);
6593 w (" Check_Type = R");
6594 w (" Target_Type = ", Int (Ttyp));
6595 pg (Union_Id (Ttyp));
6596 end if;
6597
6598 -- If we get an exception, then something went wrong, probably because of
6599 -- an error in the structure of the tree due to an incorrect program. Or
6600 -- it may be a bug in the optimization circuit. In either case the safest
6601 -- thing is simply to set the check flag unconditionally.
6602
6603 exception
6604 when others =>
6605 Activate_Range_Check (N);
6606
6607 if Debug_Flag_CC then
6608 w (" exception occurred, range flag set");
6609 end if;
6610
6611 return;
6612 end Enable_Range_Check;
6613
6614 ------------------
6615 -- Ensure_Valid --
6616 ------------------
6617
6618 procedure Ensure_Valid
6619 (Expr : Node_Id;
6620 Holes_OK : Boolean := False;
6621 Related_Id : Entity_Id := Empty;
6622 Is_Low_Bound : Boolean := False;
6623 Is_High_Bound : Boolean := False)
6624 is
6625 Typ : constant Entity_Id := Etype (Expr);
6626
6627 begin
6628 -- Ignore call if we are not doing any validity checking
6629
6630 if not Validity_Checks_On then
6631 return;
6632
6633 -- Ignore call if range or validity checks suppressed on entity or type
6634
6635 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
6636 return;
6637
6638 -- No check required if expression is from the expander, we assume the
6639 -- expander will generate whatever checks are needed. Note that this is
6640 -- not just an optimization, it avoids infinite recursions.
6641
6642 -- Unchecked conversions must be checked, unless they are initialized
6643 -- scalar values, as in a component assignment in an init proc.
6644
6645 -- In addition, we force a check if Force_Validity_Checks is set
6646
6647 elsif not Comes_From_Source (Expr)
6648 and then not
6649 (Nkind (Expr) = N_Identifier
6650 and then Present (Renamed_Object (Entity (Expr)))
6651 and then Comes_From_Source (Renamed_Object (Entity (Expr))))
6652 and then not Force_Validity_Checks
6653 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
6654 or else Kill_Range_Check (Expr))
6655 then
6656 return;
6657
6658 -- No check required if expression is known to have valid value
6659
6660 elsif Expr_Known_Valid (Expr) then
6661 return;
6662
6663 -- No check needed within a generated predicate function. Validity
6664 -- of input value will have been checked earlier.
6665
6666 elsif Ekind (Current_Scope) = E_Function
6667 and then Is_Predicate_Function (Current_Scope)
6668 then
6669 return;
6670
6671 -- Ignore case of enumeration with holes where the flag is set not to
6672 -- worry about holes, since no special validity check is needed
6673
6674 elsif Is_Enumeration_Type (Typ)
6675 and then Has_Non_Standard_Rep (Typ)
6676 and then Holes_OK
6677 then
6678 return;
6679
6680 -- No check required on the left-hand side of an assignment
6681
6682 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
6683 and then Expr = Name (Parent (Expr))
6684 then
6685 return;
6686
6687 -- No check on a universal real constant. The context will eventually
6688 -- convert it to a machine number for some target type, or report an
6689 -- illegality.
6690
6691 elsif Nkind (Expr) = N_Real_Literal
6692 and then Etype (Expr) = Universal_Real
6693 then
6694 return;
6695
6696 -- If the expression denotes a component of a packed boolean array,
6697 -- no possible check applies. We ignore the old ACATS chestnuts that
6698 -- involve Boolean range True..True.
6699
6700 -- Note: validity checks are generated for expressions that yield a
6701 -- scalar type, when it is possible to create a value that is outside of
6702 -- the type. If this is a one-bit boolean no such value exists. This is
6703 -- an optimization, and it also prevents compiler blowing up during the
6704 -- elaboration of improperly expanded packed array references.
6705
6706 elsif Nkind (Expr) = N_Indexed_Component
6707 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
6708 and then Root_Type (Etype (Expr)) = Standard_Boolean
6709 then
6710 return;
6711
6712 -- For an expression with actions, we want to insert the validity check
6713 -- on the final Expression.
6714
6715 elsif Nkind (Expr) = N_Expression_With_Actions then
6716 Ensure_Valid (Expression (Expr));
6717 return;
6718
6719 -- An annoying special case. If this is an out parameter of a scalar
6720 -- type, then the value is not going to be accessed, therefore it is
6721 -- inappropriate to do any validity check at the call site. Likewise
6722 -- if the parameter is passed by reference.
6723
6724 else
6725 -- Only need to worry about scalar types
6726
6727 if Is_Scalar_Type (Typ) then
6728 declare
6729 P : Node_Id;
6730 N : Node_Id;
6731 E : Entity_Id;
6732 F : Entity_Id;
6733 A : Node_Id;
6734 L : List_Id;
6735
6736 begin
6737 -- Find actual argument (which may be a parameter association)
6738 -- and the parent of the actual argument (the call statement)
6739
6740 N := Expr;
6741 P := Parent (Expr);
6742
6743 if Nkind (P) = N_Parameter_Association then
6744 N := P;
6745 P := Parent (N);
6746 end if;
6747
6748 -- If this is an indirect or dispatching call, get signature
6749 -- from the subprogram type.
6750
6751 if Nkind (P) in N_Entry_Call_Statement
6752 | N_Function_Call
6753 | N_Procedure_Call_Statement
6754 then
6755 E := Get_Called_Entity (P);
6756 L := Parameter_Associations (P);
6757
6758 -- Only need to worry if there are indeed actuals, and if
6759 -- this could be a subprogram call, otherwise we cannot get
6760 -- a match (either we are not an argument, or the mode of
6761 -- the formal is not OUT). This test also filters out the
6762 -- generic case.
6763
6764 if Is_Non_Empty_List (L) and then Is_Subprogram (E) then
6765
6766 -- This is the loop through parameters, looking for an
6767 -- OUT parameter for which we are the argument.
6768
6769 F := First_Formal (E);
6770 A := First (L);
6771 while Present (F) loop
6772 if A = N
6773 and then (Ekind (F) = E_Out_Parameter
6774 or else Mechanism (F) = By_Reference)
6775 then
6776 return;
6777 end if;
6778
6779 Next_Formal (F);
6780 Next (A);
6781 end loop;
6782 end if;
6783 end if;
6784 end;
6785 end if;
6786 end if;
6787
6788 -- If this is a boolean expression, only its elementary operands need
6789 -- checking: if they are valid, a boolean or short-circuit operation
6790 -- with them will be valid as well.
6791
6792 if Base_Type (Typ) = Standard_Boolean
6793 and then
6794 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
6795 then
6796 return;
6797 end if;
6798
6799 -- If we fall through, a validity check is required
6800
6801 Insert_Valid_Check (Expr, Related_Id, Is_Low_Bound, Is_High_Bound);
6802
6803 if Is_Entity_Name (Expr)
6804 and then Safe_To_Capture_Value (Expr, Entity (Expr))
6805 then
6806 Set_Is_Known_Valid (Entity (Expr));
6807 end if;
6808 end Ensure_Valid;
6809
6810 ----------------------
6811 -- Expr_Known_Valid --
6812 ----------------------
6813
6814 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
6815 Typ : constant Entity_Id := Etype (Expr);
6816
6817 begin
6818 -- Non-scalar types are always considered valid, since they never give
6819 -- rise to the issues of erroneous or bounded error behavior that are
6820 -- the concern. In formal reference manual terms the notion of validity
6821 -- only applies to scalar types. Note that even when packed arrays are
6822 -- represented using modular types, they are still arrays semantically,
6823 -- so they are also always valid (in particular, the unused bits can be
6824 -- random rubbish without affecting the validity of the array value).
6825
6826 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Impl_Type (Typ) then
6827 return True;
6828
6829 -- If no validity checking, then everything is considered valid
6830
6831 elsif not Validity_Checks_On then
6832 return True;
6833
6834 -- Floating-point types are considered valid unless floating-point
6835 -- validity checks have been specifically turned on.
6836
6837 elsif Is_Floating_Point_Type (Typ)
6838 and then not Validity_Check_Floating_Point
6839 then
6840 return True;
6841
6842 -- If the expression is the value of an object that is known to be
6843 -- valid, then clearly the expression value itself is valid.
6844
6845 elsif Is_Entity_Name (Expr)
6846 and then Is_Known_Valid (Entity (Expr))
6847
6848 -- Exclude volatile variables
6849
6850 and then not Treat_As_Volatile (Entity (Expr))
6851 then
6852 return True;
6853
6854 -- References to discriminants are always considered valid. The value
6855 -- of a discriminant gets checked when the object is built. Within the
6856 -- record, we consider it valid, and it is important to do so, since
6857 -- otherwise we can try to generate bogus validity checks which
6858 -- reference discriminants out of scope. Discriminants of concurrent
6859 -- types are excluded for the same reason.
6860
6861 elsif Is_Entity_Name (Expr)
6862 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
6863 then
6864 return True;
6865
6866 -- If the type is one for which all values are known valid, then we are
6867 -- sure that the value is valid except in the slightly odd case where
6868 -- the expression is a reference to a variable whose size has been
6869 -- explicitly set to a value greater than the object size.
6870
6871 elsif Is_Known_Valid (Typ) then
6872 if Is_Entity_Name (Expr)
6873 and then Ekind (Entity (Expr)) = E_Variable
6874 and then Esize (Entity (Expr)) > Esize (Typ)
6875 then
6876 return False;
6877 else
6878 return True;
6879 end if;
6880
6881 -- Integer and character literals always have valid values, where
6882 -- appropriate these will be range checked in any case.
6883
6884 elsif Nkind (Expr) in N_Integer_Literal | N_Character_Literal then
6885 return True;
6886
6887 -- If we have a type conversion or a qualification of a known valid
6888 -- value, then the result will always be valid.
6889
6890 elsif Nkind (Expr) in N_Type_Conversion | N_Qualified_Expression then
6891 return Expr_Known_Valid (Expression (Expr));
6892
6893 -- Case of expression is a non-floating-point operator. In this case we
6894 -- can assume the result is valid the generated code for the operator
6895 -- will include whatever checks are needed (e.g. range checks) to ensure
6896 -- validity. This assumption does not hold for the floating-point case,
6897 -- since floating-point operators can generate Infinite or NaN results
6898 -- which are considered invalid.
6899
6900 -- Historical note: in older versions, the exemption of floating-point
6901 -- types from this assumption was done only in cases where the parent
6902 -- was an assignment, function call or parameter association. Presumably
6903 -- the idea was that in other contexts, the result would be checked
6904 -- elsewhere, but this list of cases was missing tests (at least the
6905 -- N_Object_Declaration case, as shown by a reported missing validity
6906 -- check), and it is not clear why function calls but not procedure
6907 -- calls were tested for. It really seems more accurate and much
6908 -- safer to recognize that expressions which are the result of a
6909 -- floating-point operator can never be assumed to be valid.
6910
6911 elsif Nkind (Expr) in N_Op and then not Is_Floating_Point_Type (Typ) then
6912 return True;
6913
6914 -- The result of a membership test is always valid, since it is true or
6915 -- false, there are no other possibilities.
6916
6917 elsif Nkind (Expr) in N_Membership_Test then
6918 return True;
6919
6920 -- For all other cases, we do not know the expression is valid
6921
6922 else
6923 return False;
6924 end if;
6925 end Expr_Known_Valid;
6926
6927 ----------------
6928 -- Find_Check --
6929 ----------------
6930
6931 procedure Find_Check
6932 (Expr : Node_Id;
6933 Check_Type : Character;
6934 Target_Type : Entity_Id;
6935 Entry_OK : out Boolean;
6936 Check_Num : out Nat;
6937 Ent : out Entity_Id;
6938 Ofs : out Uint)
6939 is
6940 function Within_Range_Of
6941 (Target_Type : Entity_Id;
6942 Check_Type : Entity_Id) return Boolean;
6943 -- Given a requirement for checking a range against Target_Type, and
6944 -- and a range Check_Type against which a check has already been made,
6945 -- determines if the check against check type is sufficient to ensure
6946 -- that no check against Target_Type is required.
6947
6948 ---------------------
6949 -- Within_Range_Of --
6950 ---------------------
6951
6952 function Within_Range_Of
6953 (Target_Type : Entity_Id;
6954 Check_Type : Entity_Id) return Boolean
6955 is
6956 begin
6957 if Target_Type = Check_Type then
6958 return True;
6959
6960 else
6961 declare
6962 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
6963 Thi : constant Node_Id := Type_High_Bound (Target_Type);
6964 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
6965 Chi : constant Node_Id := Type_High_Bound (Check_Type);
6966
6967 begin
6968 if (Tlo = Clo
6969 or else (Compile_Time_Known_Value (Tlo)
6970 and then
6971 Compile_Time_Known_Value (Clo)
6972 and then
6973 Expr_Value (Clo) >= Expr_Value (Tlo)))
6974 and then
6975 (Thi = Chi
6976 or else (Compile_Time_Known_Value (Thi)
6977 and then
6978 Compile_Time_Known_Value (Chi)
6979 and then
6980 Expr_Value (Chi) <= Expr_Value (Clo)))
6981 then
6982 return True;
6983 else
6984 return False;
6985 end if;
6986 end;
6987 end if;
6988 end Within_Range_Of;
6989
6990 -- Start of processing for Find_Check
6991
6992 begin
6993 -- Establish default, in case no entry is found
6994
6995 Check_Num := 0;
6996
6997 -- Case of expression is simple entity reference
6998
6999 if Is_Entity_Name (Expr) then
7000 Ent := Entity (Expr);
7001 Ofs := Uint_0;
7002
7003 -- Case of expression is entity + known constant
7004
7005 elsif Nkind (Expr) = N_Op_Add
7006 and then Compile_Time_Known_Value (Right_Opnd (Expr))
7007 and then Is_Entity_Name (Left_Opnd (Expr))
7008 then
7009 Ent := Entity (Left_Opnd (Expr));
7010 Ofs := Expr_Value (Right_Opnd (Expr));
7011
7012 -- Case of expression is entity - known constant
7013
7014 elsif Nkind (Expr) = N_Op_Subtract
7015 and then Compile_Time_Known_Value (Right_Opnd (Expr))
7016 and then Is_Entity_Name (Left_Opnd (Expr))
7017 then
7018 Ent := Entity (Left_Opnd (Expr));
7019 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
7020
7021 -- Any other expression is not of the right form
7022
7023 else
7024 Ent := Empty;
7025 Ofs := Uint_0;
7026 Entry_OK := False;
7027 return;
7028 end if;
7029
7030 -- Come here with expression of appropriate form, check if entity is an
7031 -- appropriate one for our purposes.
7032
7033 if (Ekind (Ent) = E_Variable
7034 or else Is_Constant_Object (Ent))
7035 and then not Is_Library_Level_Entity (Ent)
7036 then
7037 Entry_OK := True;
7038 else
7039 Entry_OK := False;
7040 return;
7041 end if;
7042
7043 -- See if there is matching check already
7044
7045 for J in reverse 1 .. Num_Saved_Checks loop
7046 declare
7047 SC : Saved_Check renames Saved_Checks (J);
7048 begin
7049 if SC.Killed = False
7050 and then SC.Entity = Ent
7051 and then SC.Offset = Ofs
7052 and then SC.Check_Type = Check_Type
7053 and then Within_Range_Of (Target_Type, SC.Target_Type)
7054 then
7055 Check_Num := J;
7056 return;
7057 end if;
7058 end;
7059 end loop;
7060
7061 -- If we fall through entry was not found
7062
7063 return;
7064 end Find_Check;
7065
7066 ---------------------------------
7067 -- Generate_Discriminant_Check --
7068 ---------------------------------
7069
7070 procedure Generate_Discriminant_Check (N : Node_Id) is
7071 Loc : constant Source_Ptr := Sloc (N);
7072 Pref : constant Node_Id := Prefix (N);
7073 Sel : constant Node_Id := Selector_Name (N);
7074
7075 Orig_Comp : constant Entity_Id :=
7076 Original_Record_Component (Entity (Sel));
7077 -- The original component to be checked
7078
7079 Discr_Fct : constant Entity_Id :=
7080 Discriminant_Checking_Func (Orig_Comp);
7081 -- The discriminant checking function
7082
7083 Discr : Entity_Id;
7084 -- One discriminant to be checked in the type
7085
7086 Real_Discr : Entity_Id;
7087 -- Actual discriminant in the call
7088
7089 Pref_Type : Entity_Id;
7090 -- Type of relevant prefix (ignoring private/access stuff)
7091
7092 Args : List_Id;
7093 -- List of arguments for function call
7094
7095 Formal : Entity_Id;
7096 -- Keep track of the formal corresponding to the actual we build for
7097 -- each discriminant, in order to be able to perform the necessary type
7098 -- conversions.
7099
7100 Scomp : Node_Id;
7101 -- Selected component reference for checking function argument
7102
7103 begin
7104 Pref_Type := Etype (Pref);
7105
7106 -- Force evaluation of the prefix, so that it does not get evaluated
7107 -- twice (once for the check, once for the actual reference). Such a
7108 -- double evaluation is always a potential source of inefficiency, and
7109 -- is functionally incorrect in the volatile case, or when the prefix
7110 -- may have side effects. A nonvolatile entity or a component of a
7111 -- nonvolatile entity requires no evaluation.
7112
7113 if Is_Entity_Name (Pref) then
7114 if Treat_As_Volatile (Entity (Pref)) then
7115 Force_Evaluation (Pref, Name_Req => True);
7116 end if;
7117
7118 elsif Treat_As_Volatile (Etype (Pref)) then
7119 Force_Evaluation (Pref, Name_Req => True);
7120
7121 elsif Nkind (Pref) = N_Selected_Component
7122 and then Is_Entity_Name (Prefix (Pref))
7123 then
7124 null;
7125
7126 else
7127 Force_Evaluation (Pref, Name_Req => True);
7128 end if;
7129
7130 -- For a tagged type, use the scope of the original component to
7131 -- obtain the type, because ???
7132
7133 if Is_Tagged_Type (Scope (Orig_Comp)) then
7134 Pref_Type := Scope (Orig_Comp);
7135
7136 -- For an untagged derived type, use the discriminants of the parent
7137 -- which have been renamed in the derivation, possibly by a one-to-many
7138 -- discriminant constraint. For untagged type, initially get the Etype
7139 -- of the prefix
7140
7141 else
7142 if Is_Derived_Type (Pref_Type)
7143 and then Number_Discriminants (Pref_Type) /=
7144 Number_Discriminants (Etype (Base_Type (Pref_Type)))
7145 then
7146 Pref_Type := Etype (Base_Type (Pref_Type));
7147 end if;
7148 end if;
7149
7150 -- We definitely should have a checking function, This routine should
7151 -- not be called if no discriminant checking function is present.
7152
7153 pragma Assert (Present (Discr_Fct));
7154
7155 -- Create the list of the actual parameters for the call. This list
7156 -- is the list of the discriminant fields of the record expression to
7157 -- be discriminant checked.
7158
7159 Args := New_List;
7160 Formal := First_Formal (Discr_Fct);
7161 Discr := First_Discriminant (Pref_Type);
7162 while Present (Discr) loop
7163
7164 -- If we have a corresponding discriminant field, and a parent
7165 -- subtype is present, then we want to use the corresponding
7166 -- discriminant since this is the one with the useful value.
7167
7168 if Present (Corresponding_Discriminant (Discr))
7169 and then Ekind (Pref_Type) = E_Record_Type
7170 and then Present (Parent_Subtype (Pref_Type))
7171 then
7172 Real_Discr := Corresponding_Discriminant (Discr);
7173 else
7174 Real_Discr := Discr;
7175 end if;
7176
7177 -- Construct the reference to the discriminant
7178
7179 Scomp :=
7180 Make_Selected_Component (Loc,
7181 Prefix =>
7182 Unchecked_Convert_To (Pref_Type,
7183 Duplicate_Subexpr (Pref)),
7184 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
7185
7186 -- Manually analyze and resolve this selected component. We really
7187 -- want it just as it appears above, and do not want the expander
7188 -- playing discriminal games etc with this reference. Then we append
7189 -- the argument to the list we are gathering.
7190
7191 Set_Etype (Scomp, Etype (Real_Discr));
7192 Set_Analyzed (Scomp, True);
7193 Append_To (Args, Convert_To (Etype (Formal), Scomp));
7194
7195 Next_Formal_With_Extras (Formal);
7196 Next_Discriminant (Discr);
7197 end loop;
7198
7199 -- Now build and insert the call
7200
7201 Insert_Action (N,
7202 Make_Raise_Constraint_Error (Loc,
7203 Condition =>
7204 Make_Function_Call (Loc,
7205 Name => New_Occurrence_Of (Discr_Fct, Loc),
7206 Parameter_Associations => Args),
7207 Reason => CE_Discriminant_Check_Failed));
7208 end Generate_Discriminant_Check;
7209
7210 ---------------------------
7211 -- Generate_Index_Checks --
7212 ---------------------------
7213
7214 procedure Generate_Index_Checks (N : Node_Id) is
7215
7216 function Entity_Of_Prefix return Entity_Id;
7217 -- Returns the entity of the prefix of N (or Empty if not found)
7218
7219 ----------------------
7220 -- Entity_Of_Prefix --
7221 ----------------------
7222
7223 function Entity_Of_Prefix return Entity_Id is
7224 P : Node_Id;
7225
7226 begin
7227 P := Prefix (N);
7228 while not Is_Entity_Name (P) loop
7229 if Nkind (P) not in N_Selected_Component | N_Indexed_Component then
7230 return Empty;
7231 end if;
7232
7233 P := Prefix (P);
7234 end loop;
7235
7236 return Entity (P);
7237 end Entity_Of_Prefix;
7238
7239 -- Local variables
7240
7241 Loc : constant Source_Ptr := Sloc (N);
7242 A : constant Node_Id := Prefix (N);
7243 A_Ent : constant Entity_Id := Entity_Of_Prefix;
7244 Sub : Node_Id;
7245
7246 -- Start of processing for Generate_Index_Checks
7247
7248 begin
7249 -- Ignore call if the prefix is not an array since we have a serious
7250 -- error in the sources. Ignore it also if index checks are suppressed
7251 -- for array object or type.
7252
7253 if not Is_Array_Type (Etype (A))
7254 or else (Present (A_Ent) and then Index_Checks_Suppressed (A_Ent))
7255 or else Index_Checks_Suppressed (Etype (A))
7256 then
7257 return;
7258
7259 -- The indexed component we are dealing with contains 'Loop_Entry in its
7260 -- prefix. This case arises when analysis has determined that constructs
7261 -- such as
7262
7263 -- Prefix'Loop_Entry (Expr)
7264 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
7265
7266 -- require rewriting for error detection purposes. A side effect of this
7267 -- action is the generation of index checks that mention 'Loop_Entry.
7268 -- Delay the generation of the check until 'Loop_Entry has been properly
7269 -- expanded. This is done in Expand_Loop_Entry_Attributes.
7270
7271 elsif Nkind (Prefix (N)) = N_Attribute_Reference
7272 and then Attribute_Name (Prefix (N)) = Name_Loop_Entry
7273 then
7274 return;
7275 end if;
7276
7277 -- Generate a raise of constraint error with the appropriate reason and
7278 -- a condition of the form:
7279
7280 -- Base_Type (Sub) not in Array'Range (Subscript)
7281
7282 -- Note that the reason we generate the conversion to the base type here
7283 -- is that we definitely want the range check to take place, even if it
7284 -- looks like the subtype is OK. Optimization considerations that allow
7285 -- us to omit the check have already been taken into account in the
7286 -- setting of the Do_Range_Check flag earlier on.
7287
7288 Sub := First (Expressions (N));
7289
7290 -- Handle string literals
7291
7292 if Ekind (Etype (A)) = E_String_Literal_Subtype then
7293 if Do_Range_Check (Sub) then
7294 Set_Do_Range_Check (Sub, False);
7295
7296 -- For string literals we obtain the bounds of the string from the
7297 -- associated subtype.
7298
7299 Insert_Action (N,
7300 Make_Raise_Constraint_Error (Loc,
7301 Condition =>
7302 Make_Not_In (Loc,
7303 Left_Opnd =>
7304 Convert_To (Base_Type (Etype (Sub)),
7305 Duplicate_Subexpr_Move_Checks (Sub)),
7306 Right_Opnd =>
7307 Make_Attribute_Reference (Loc,
7308 Prefix => New_Occurrence_Of (Etype (A), Loc),
7309 Attribute_Name => Name_Range)),
7310 Reason => CE_Index_Check_Failed));
7311 end if;
7312
7313 -- General case
7314
7315 else
7316 declare
7317 A_Idx : Node_Id;
7318 A_Range : Node_Id;
7319 Ind : Pos;
7320 Num : List_Id;
7321 Range_N : Node_Id;
7322
7323 begin
7324 A_Idx := First_Index (Etype (A));
7325 Ind := 1;
7326 while Present (Sub) loop
7327 if Do_Range_Check (Sub) then
7328 Set_Do_Range_Check (Sub, False);
7329
7330 -- Force evaluation except for the case of a simple name of
7331 -- a nonvolatile entity.
7332
7333 if not Is_Entity_Name (Sub)
7334 or else Treat_As_Volatile (Entity (Sub))
7335 then
7336 Force_Evaluation (Sub);
7337 end if;
7338
7339 if Nkind (A_Idx) = N_Range then
7340 A_Range := A_Idx;
7341
7342 elsif Nkind (A_Idx) in N_Identifier | N_Expanded_Name then
7343 A_Range := Scalar_Range (Entity (A_Idx));
7344
7345 if Nkind (A_Range) = N_Subtype_Indication then
7346 A_Range := Range_Expression (Constraint (A_Range));
7347 end if;
7348
7349 else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
7350 A_Range := Range_Expression (Constraint (A_Idx));
7351 end if;
7352
7353 -- For array objects with constant bounds we can generate
7354 -- the index check using the bounds of the type of the index
7355
7356 if Present (A_Ent)
7357 and then Ekind (A_Ent) = E_Variable
7358 and then Is_Constant_Bound (Low_Bound (A_Range))
7359 and then Is_Constant_Bound (High_Bound (A_Range))
7360 then
7361 Range_N :=
7362 Make_Attribute_Reference (Loc,
7363 Prefix =>
7364 New_Occurrence_Of (Etype (A_Idx), Loc),
7365 Attribute_Name => Name_Range);
7366
7367 -- For arrays with non-constant bounds we cannot generate
7368 -- the index check using the bounds of the type of the index
7369 -- since it may reference discriminants of some enclosing
7370 -- type. We obtain the bounds directly from the prefix
7371 -- object.
7372
7373 else
7374 if Ind = 1 then
7375 Num := No_List;
7376 else
7377 Num := New_List (Make_Integer_Literal (Loc, Ind));
7378 end if;
7379
7380 Range_N :=
7381 Make_Attribute_Reference (Loc,
7382 Prefix =>
7383 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
7384 Attribute_Name => Name_Range,
7385 Expressions => Num);
7386 end if;
7387
7388 Insert_Action (N,
7389 Make_Raise_Constraint_Error (Loc,
7390 Condition =>
7391 Make_Not_In (Loc,
7392 Left_Opnd =>
7393 Convert_To (Base_Type (Etype (Sub)),
7394 Duplicate_Subexpr_Move_Checks (Sub)),
7395 Right_Opnd => Range_N),
7396 Reason => CE_Index_Check_Failed));
7397 end if;
7398
7399 Next_Index (A_Idx);
7400 Ind := Ind + 1;
7401 Next (Sub);
7402 end loop;
7403 end;
7404 end if;
7405 end Generate_Index_Checks;
7406
7407 --------------------------
7408 -- Generate_Range_Check --
7409 --------------------------
7410
7411 procedure Generate_Range_Check
7412 (N : Node_Id;
7413 Target_Type : Entity_Id;
7414 Reason : RT_Exception_Code)
7415 is
7416 Loc : constant Source_Ptr := Sloc (N);
7417 Source_Type : constant Entity_Id := Etype (N);
7418 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
7419 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
7420
7421 procedure Convert_And_Check_Range (Suppress : Check_Id);
7422 -- Convert N to the target base type and save the result in a temporary.
7423 -- The action is analyzed using the default checks as modified by the
7424 -- given Suppress argument. Then check the converted value against the
7425 -- range of the target subtype.
7426
7427 function Is_Single_Attribute_Reference (N : Node_Id) return Boolean;
7428 -- Return True if N is an expression that contains a single attribute
7429 -- reference, possibly as operand among only integer literal operands.
7430
7431 -----------------------------
7432 -- Convert_And_Check_Range --
7433 -----------------------------
7434
7435 procedure Convert_And_Check_Range (Suppress : Check_Id) is
7436 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7437 Conv_N : Node_Id;
7438
7439 begin
7440 -- For enumeration types with non-standard representation this is a
7441 -- direct conversion from the enumeration type to the target integer
7442 -- type, which is treated by the back end as a normal integer type
7443 -- conversion, treating the enumeration type as an integer, which is
7444 -- exactly what we want. We set Conversion_OK to make sure that the
7445 -- analyzer does not complain about what otherwise might be an
7446 -- illegal conversion.
7447
7448 if Is_Enumeration_Type (Source_Base_Type)
7449 and then Present (Enum_Pos_To_Rep (Source_Base_Type))
7450 and then Is_Integer_Type (Target_Base_Type)
7451 then
7452 Conv_N := OK_Convert_To (Target_Base_Type, Duplicate_Subexpr (N));
7453 else
7454 Conv_N := Convert_To (Target_Base_Type, Duplicate_Subexpr (N));
7455 end if;
7456
7457 -- We make a temporary to hold the value of the conversion to the
7458 -- target base type, and then do the test against this temporary.
7459 -- N itself is replaced by an occurrence of Tnn and followed by
7460 -- the explicit range check.
7461
7462 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
7463 -- [constraint_error when Tnn not in Target_Type]
7464 -- Tnn
7465
7466 Insert_Actions (N, New_List (
7467 Make_Object_Declaration (Loc,
7468 Defining_Identifier => Tnn,
7469 Object_Definition => New_Occurrence_Of (Target_Base_Type, Loc),
7470 Constant_Present => True,
7471 Expression => Conv_N),
7472
7473 Make_Raise_Constraint_Error (Loc,
7474 Condition =>
7475 Make_Not_In (Loc,
7476 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
7477 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
7478 Reason => Reason)),
7479 Suppress => Suppress);
7480
7481 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
7482
7483 -- Set the type of N, because the declaration for Tnn might not
7484 -- be analyzed yet, as is the case if N appears within a record
7485 -- declaration, as a discriminant constraint or expression.
7486
7487 Set_Etype (N, Target_Base_Type);
7488 end Convert_And_Check_Range;
7489
7490 -------------------------------------
7491 -- Is_Single_Attribute_Reference --
7492 -------------------------------------
7493
7494 function Is_Single_Attribute_Reference (N : Node_Id) return Boolean is
7495 begin
7496 if Nkind (N) = N_Attribute_Reference then
7497 return True;
7498
7499 elsif Nkind (N) in N_Binary_Op then
7500 if Nkind (Right_Opnd (N)) = N_Integer_Literal then
7501 return Is_Single_Attribute_Reference (Left_Opnd (N));
7502
7503 elsif Nkind (Left_Opnd (N)) = N_Integer_Literal then
7504 return Is_Single_Attribute_Reference (Right_Opnd (N));
7505
7506 else
7507 return False;
7508 end if;
7509
7510 else
7511 return False;
7512 end if;
7513 end Is_Single_Attribute_Reference;
7514
7515 -- Start of processing for Generate_Range_Check
7516
7517 begin
7518 -- First special case, if the source type is already within the range
7519 -- of the target type, then no check is needed (probably we should have
7520 -- stopped Do_Range_Check from being set in the first place, but better
7521 -- late than never in preventing junk code and junk flag settings).
7522
7523 if In_Subrange_Of (Source_Type, Target_Type)
7524
7525 -- We do NOT apply this if the source node is a literal, since in this
7526 -- case the literal has already been labeled as having the subtype of
7527 -- the target.
7528
7529 and then not
7530 (Nkind (N) in
7531 N_Integer_Literal | N_Real_Literal | N_Character_Literal
7532 or else
7533 (Is_Entity_Name (N)
7534 and then Ekind (Entity (N)) = E_Enumeration_Literal))
7535 then
7536 Set_Do_Range_Check (N, False);
7537 return;
7538 end if;
7539
7540 -- Here a check is needed. If the expander is not active (which is also
7541 -- the case in GNATprove mode), then simply set the Do_Range_Check flag
7542 -- and we are done. We just want to see the range check flag set, we do
7543 -- not want to generate the explicit range check code.
7544
7545 if not Expander_Active then
7546 Set_Do_Range_Check (N);
7547 return;
7548 end if;
7549
7550 -- Here we will generate an explicit range check, so we don't want to
7551 -- set the Do_Range check flag, since the range check is taken care of
7552 -- by the code we will generate.
7553
7554 Set_Do_Range_Check (N, False);
7555
7556 -- Force evaluation of the node, so that it does not get evaluated twice
7557 -- (once for the check, once for the actual reference). Such a double
7558 -- evaluation is always a potential source of inefficiency, and is
7559 -- functionally incorrect in the volatile case.
7560
7561 -- We skip the evaluation of attribute references because, after these
7562 -- runtime checks are generated, the expander may need to rewrite this
7563 -- node (for example, see Attribute_Max_Size_In_Storage_Elements in
7564 -- Expand_N_Attribute_Reference) and, in many cases, their return type
7565 -- is universal integer, which is a very large type for a temporary.
7566
7567 if not Is_Single_Attribute_Reference (N)
7568 and then (not Is_Entity_Name (N)
7569 or else Treat_As_Volatile (Entity (N)))
7570 then
7571 Force_Evaluation (N, Mode => Strict);
7572 end if;
7573
7574 -- The easiest case is when Source_Base_Type and Target_Base_Type are
7575 -- the same since in this case we can simply do a direct check of the
7576 -- value of N against the bounds of Target_Type.
7577
7578 -- [constraint_error when N not in Target_Type]
7579
7580 -- Note: this is by far the most common case, for example all cases of
7581 -- checks on the RHS of assignments are in this category, but not all
7582 -- cases are like this. Notably conversions can involve two types.
7583
7584 if Source_Base_Type = Target_Base_Type then
7585
7586 -- Insert the explicit range check. Note that we suppress checks for
7587 -- this code, since we don't want a recursive range check popping up.
7588
7589 Insert_Action (N,
7590 Make_Raise_Constraint_Error (Loc,
7591 Condition =>
7592 Make_Not_In (Loc,
7593 Left_Opnd => Duplicate_Subexpr (N),
7594 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
7595 Reason => Reason),
7596 Suppress => All_Checks);
7597
7598 -- Next test for the case where the target type is within the bounds
7599 -- of the base type of the source type, since in this case we can
7600 -- simply convert the bounds of the target type to this base type
7601 -- to do the test.
7602
7603 -- [constraint_error when N not in
7604 -- Source_Base_Type (Target_Type'First)
7605 -- ..
7606 -- Source_Base_Type(Target_Type'Last))]
7607
7608 -- The conversions will always work and need no check
7609
7610 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
7611 -- of converting from an enumeration value to an integer type, such as
7612 -- occurs for the case of generating a range check on Enum'Val(Exp)
7613 -- (which used to be handled by gigi). This is OK, since the conversion
7614 -- itself does not require a check.
7615
7616 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
7617
7618 -- Insert the explicit range check. Note that we suppress checks for
7619 -- this code, since we don't want a recursive range check popping up.
7620
7621 if Is_Discrete_Type (Source_Base_Type)
7622 and then
7623 Is_Discrete_Type (Target_Base_Type)
7624 then
7625 Insert_Action (N,
7626 Make_Raise_Constraint_Error (Loc,
7627 Condition =>
7628 Make_Not_In (Loc,
7629 Left_Opnd => Duplicate_Subexpr (N),
7630
7631 Right_Opnd =>
7632 Make_Range (Loc,
7633 Low_Bound =>
7634 Unchecked_Convert_To (Source_Base_Type,
7635 Make_Attribute_Reference (Loc,
7636 Prefix =>
7637 New_Occurrence_Of (Target_Type, Loc),
7638 Attribute_Name => Name_First)),
7639
7640 High_Bound =>
7641 Unchecked_Convert_To (Source_Base_Type,
7642 Make_Attribute_Reference (Loc,
7643 Prefix =>
7644 New_Occurrence_Of (Target_Type, Loc),
7645 Attribute_Name => Name_Last)))),
7646 Reason => Reason),
7647 Suppress => All_Checks);
7648
7649 -- For conversions involving at least one type that is not discrete,
7650 -- first convert to the target base type and then generate the range
7651 -- check. This avoids problems with values that are close to a bound
7652 -- of the target type that would fail a range check when done in a
7653 -- larger source type before converting but pass if converted with
7654 -- rounding and then checked (such as in float-to-float conversions).
7655
7656 -- Note that overflow checks are not suppressed for this code because
7657 -- we do not know whether the source type is in range of the target
7658 -- base type (unlike in the next case below).
7659
7660 else
7661 Convert_And_Check_Range (Suppress => Range_Check);
7662 end if;
7663
7664 -- Note that at this stage we know that the Target_Base_Type is not in
7665 -- the range of the Source_Base_Type (since even the Target_Type itself
7666 -- is not in this range). It could still be the case that Source_Type is
7667 -- in range of the target base type since we have not checked that case.
7668
7669 -- If that is the case, we can freely convert the source to the target,
7670 -- and then test the target result against the bounds. Note that checks
7671 -- are suppressed for this code, since we don't want a recursive range
7672 -- check popping up.
7673
7674 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
7675 Convert_And_Check_Range (Suppress => All_Checks);
7676
7677 -- At this stage, we know that we have two scalar types, which are
7678 -- directly convertible, and where neither scalar type has a base
7679 -- range that is in the range of the other scalar type.
7680
7681 -- The only way this can happen is with a signed and unsigned type.
7682 -- So test for these two cases:
7683
7684 else
7685 -- Case of the source is unsigned and the target is signed
7686
7687 if Is_Unsigned_Type (Source_Base_Type)
7688 and then not Is_Unsigned_Type (Target_Base_Type)
7689 then
7690 -- If the source is unsigned and the target is signed, then we
7691 -- know that the source is not shorter than the target (otherwise
7692 -- the source base type would be in the target base type range).
7693
7694 -- In other words, the unsigned type is either the same size as
7695 -- the target, or it is larger. It cannot be smaller.
7696
7697 pragma Assert
7698 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
7699
7700 -- We only need to check the low bound if the low bound of the
7701 -- target type is non-negative. If the low bound of the target
7702 -- type is negative, then we know that we will fit fine.
7703
7704 -- If the high bound of the target type is negative, then we
7705 -- know we have a constraint error, since we can't possibly
7706 -- have a negative source.
7707
7708 -- With these two checks out of the way, we can do the check
7709 -- using the source type safely
7710
7711 -- This is definitely the most annoying case.
7712
7713 -- [constraint_error
7714 -- when (Target_Type'First >= 0
7715 -- and then
7716 -- N < Source_Base_Type (Target_Type'First))
7717 -- or else Target_Type'Last < 0
7718 -- or else N > Source_Base_Type (Target_Type'Last)];
7719
7720 -- We turn off all checks since we know that the conversions
7721 -- will work fine, given the guards for negative values.
7722
7723 Insert_Action (N,
7724 Make_Raise_Constraint_Error (Loc,
7725 Condition =>
7726 Make_Or_Else (Loc,
7727 Make_Or_Else (Loc,
7728 Left_Opnd =>
7729 Make_And_Then (Loc,
7730 Left_Opnd => Make_Op_Ge (Loc,
7731 Left_Opnd =>
7732 Make_Attribute_Reference (Loc,
7733 Prefix =>
7734 New_Occurrence_Of (Target_Type, Loc),
7735 Attribute_Name => Name_First),
7736 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7737
7738 Right_Opnd =>
7739 Make_Op_Lt (Loc,
7740 Left_Opnd => Duplicate_Subexpr (N),
7741 Right_Opnd =>
7742 Convert_To (Source_Base_Type,
7743 Make_Attribute_Reference (Loc,
7744 Prefix =>
7745 New_Occurrence_Of (Target_Type, Loc),
7746 Attribute_Name => Name_First)))),
7747
7748 Right_Opnd =>
7749 Make_Op_Lt (Loc,
7750 Left_Opnd =>
7751 Make_Attribute_Reference (Loc,
7752 Prefix => New_Occurrence_Of (Target_Type, Loc),
7753 Attribute_Name => Name_Last),
7754 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
7755
7756 Right_Opnd =>
7757 Make_Op_Gt (Loc,
7758 Left_Opnd => Duplicate_Subexpr (N),
7759 Right_Opnd =>
7760 Convert_To (Source_Base_Type,
7761 Make_Attribute_Reference (Loc,
7762 Prefix => New_Occurrence_Of (Target_Type, Loc),
7763 Attribute_Name => Name_Last)))),
7764
7765 Reason => Reason),
7766 Suppress => All_Checks);
7767
7768 -- Only remaining possibility is that the source is signed and
7769 -- the target is unsigned.
7770
7771 else
7772 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
7773 and then Is_Unsigned_Type (Target_Base_Type));
7774
7775 -- If the source is signed and the target is unsigned, then we
7776 -- know that the target is not shorter than the source (otherwise
7777 -- the target base type would be in the source base type range).
7778
7779 -- In other words, the unsigned type is either the same size as
7780 -- the target, or it is larger. It cannot be smaller.
7781
7782 -- Clearly we have an error if the source value is negative since
7783 -- no unsigned type can have negative values. If the source type
7784 -- is non-negative, then the check can be done using the target
7785 -- type.
7786
7787 -- Tnn : constant Target_Base_Type (N) := Target_Type;
7788
7789 -- [constraint_error
7790 -- when N < 0 or else Tnn not in Target_Type];
7791
7792 -- We turn off all checks for the conversion of N to the target
7793 -- base type, since we generate the explicit check to ensure that
7794 -- the value is non-negative
7795
7796 declare
7797 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7798
7799 begin
7800 Insert_Actions (N, New_List (
7801 Make_Object_Declaration (Loc,
7802 Defining_Identifier => Tnn,
7803 Object_Definition =>
7804 New_Occurrence_Of (Target_Base_Type, Loc),
7805 Constant_Present => True,
7806 Expression =>
7807 Make_Unchecked_Type_Conversion (Loc,
7808 Subtype_Mark =>
7809 New_Occurrence_Of (Target_Base_Type, Loc),
7810 Expression => Duplicate_Subexpr (N))),
7811
7812 Make_Raise_Constraint_Error (Loc,
7813 Condition =>
7814 Make_Or_Else (Loc,
7815 Left_Opnd =>
7816 Make_Op_Lt (Loc,
7817 Left_Opnd => Duplicate_Subexpr (N),
7818 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7819
7820 Right_Opnd =>
7821 Make_Not_In (Loc,
7822 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
7823 Right_Opnd =>
7824 New_Occurrence_Of (Target_Type, Loc))),
7825
7826 Reason => Reason)),
7827 Suppress => All_Checks);
7828
7829 -- Set the Etype explicitly, because Insert_Actions may have
7830 -- placed the declaration in the freeze list for an enclosing
7831 -- construct, and thus it is not analyzed yet.
7832
7833 Set_Etype (Tnn, Target_Base_Type);
7834 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
7835 end;
7836 end if;
7837 end if;
7838 end Generate_Range_Check;
7839
7840 ------------------
7841 -- Get_Check_Id --
7842 ------------------
7843
7844 function Get_Check_Id (N : Name_Id) return Check_Id is
7845 begin
7846 -- For standard check name, we can do a direct computation
7847
7848 if N in First_Check_Name .. Last_Check_Name then
7849 return Check_Id (N - (First_Check_Name - 1));
7850
7851 -- For non-standard names added by pragma Check_Name, search table
7852
7853 else
7854 for J in All_Checks + 1 .. Check_Names.Last loop
7855 if Check_Names.Table (J) = N then
7856 return J;
7857 end if;
7858 end loop;
7859 end if;
7860
7861 -- No matching name found
7862
7863 return No_Check_Id;
7864 end Get_Check_Id;
7865
7866 ---------------------
7867 -- Get_Discriminal --
7868 ---------------------
7869
7870 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
7871 Loc : constant Source_Ptr := Sloc (E);
7872 D : Entity_Id;
7873 Sc : Entity_Id;
7874
7875 begin
7876 -- The bound can be a bona fide parameter of a protected operation,
7877 -- rather than a prival encoded as an in-parameter.
7878
7879 if No (Discriminal_Link (Entity (Bound))) then
7880 return Bound;
7881 end if;
7882
7883 -- Climb the scope stack looking for an enclosing protected type. If
7884 -- we run out of scopes, return the bound itself.
7885
7886 Sc := Scope (E);
7887 while Present (Sc) loop
7888 if Sc = Standard_Standard then
7889 return Bound;
7890 elsif Ekind (Sc) = E_Protected_Type then
7891 exit;
7892 end if;
7893
7894 Sc := Scope (Sc);
7895 end loop;
7896
7897 D := First_Discriminant (Sc);
7898 while Present (D) loop
7899 if Chars (D) = Chars (Bound) then
7900 return New_Occurrence_Of (Discriminal (D), Loc);
7901 end if;
7902
7903 Next_Discriminant (D);
7904 end loop;
7905
7906 return Bound;
7907 end Get_Discriminal;
7908
7909 ----------------------
7910 -- Get_Range_Checks --
7911 ----------------------
7912
7913 function Get_Range_Checks
7914 (Expr : Node_Id;
7915 Target_Typ : Entity_Id;
7916 Source_Typ : Entity_Id := Empty;
7917 Warn_Node : Node_Id := Empty) return Check_Result
7918 is
7919 begin
7920 return
7921 Selected_Range_Checks (Expr, Target_Typ, Source_Typ, Warn_Node);
7922 end Get_Range_Checks;
7923
7924 ------------------
7925 -- Guard_Access --
7926 ------------------
7927
7928 function Guard_Access
7929 (Cond : Node_Id;
7930 Loc : Source_Ptr;
7931 Expr : Node_Id) return Node_Id
7932 is
7933 begin
7934 if Nkind (Cond) = N_Or_Else then
7935 Set_Paren_Count (Cond, 1);
7936 end if;
7937
7938 if Nkind (Expr) = N_Allocator then
7939 return Cond;
7940
7941 else
7942 return
7943 Make_And_Then (Loc,
7944 Left_Opnd =>
7945 Make_Op_Ne (Loc,
7946 Left_Opnd => Duplicate_Subexpr_No_Checks (Expr),
7947 Right_Opnd => Make_Null (Loc)),
7948 Right_Opnd => Cond);
7949 end if;
7950 end Guard_Access;
7951
7952 -----------------------------
7953 -- Index_Checks_Suppressed --
7954 -----------------------------
7955
7956 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
7957 begin
7958 if Present (E) and then Checks_May_Be_Suppressed (E) then
7959 return Is_Check_Suppressed (E, Index_Check);
7960 else
7961 return Scope_Suppress.Suppress (Index_Check);
7962 end if;
7963 end Index_Checks_Suppressed;
7964
7965 ----------------
7966 -- Initialize --
7967 ----------------
7968
7969 procedure Initialize is
7970 begin
7971 for J in Determine_Range_Cache_N'Range loop
7972 Determine_Range_Cache_N (J) := Empty;
7973 end loop;
7974
7975 Check_Names.Init;
7976
7977 for J in Int range 1 .. All_Checks loop
7978 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
7979 end loop;
7980 end Initialize;
7981
7982 -------------------------
7983 -- Insert_Range_Checks --
7984 -------------------------
7985
7986 procedure Insert_Range_Checks
7987 (Checks : Check_Result;
7988 Node : Node_Id;
7989 Suppress_Typ : Entity_Id;
7990 Static_Sloc : Source_Ptr;
7991 Do_Before : Boolean := False)
7992 is
7993 Checks_On : constant Boolean :=
7994 not Index_Checks_Suppressed (Suppress_Typ)
7995 or else
7996 not Range_Checks_Suppressed (Suppress_Typ);
7997
7998 Check_Node : Node_Id;
7999
8000 begin
8001 -- For now we just return if Checks_On is false, however this should be
8002 -- enhanced to check for an always True value in the condition and to
8003 -- generate a compilation warning.
8004
8005 if not Expander_Active or not Checks_On then
8006 return;
8007 end if;
8008
8009 for J in 1 .. 2 loop
8010 exit when No (Checks (J));
8011
8012 if Nkind (Checks (J)) = N_Raise_Constraint_Error
8013 and then Present (Condition (Checks (J)))
8014 then
8015 Check_Node := Checks (J);
8016 else
8017 Check_Node :=
8018 Make_Raise_Constraint_Error (Static_Sloc,
8019 Reason => CE_Range_Check_Failed);
8020 end if;
8021
8022 Mark_Rewrite_Insertion (Check_Node);
8023
8024 if Do_Before then
8025 Insert_Before_And_Analyze (Node, Check_Node);
8026 else
8027 Insert_After_And_Analyze (Node, Check_Node);
8028 end if;
8029 end loop;
8030 end Insert_Range_Checks;
8031
8032 ------------------------
8033 -- Insert_Valid_Check --
8034 ------------------------
8035
8036 procedure Insert_Valid_Check
8037 (Expr : Node_Id;
8038 Related_Id : Entity_Id := Empty;
8039 Is_Low_Bound : Boolean := False;
8040 Is_High_Bound : Boolean := False)
8041 is
8042 Loc : constant Source_Ptr := Sloc (Expr);
8043 Typ : constant Entity_Id := Etype (Expr);
8044 Exp : Node_Id;
8045
8046 begin
8047 -- Do not insert if checks off, or if not checking validity or if
8048 -- expression is known to be valid.
8049
8050 if not Validity_Checks_On
8051 or else Range_Or_Validity_Checks_Suppressed (Expr)
8052 or else Expr_Known_Valid (Expr)
8053 then
8054 return;
8055
8056 -- Do not insert checks within a predicate function. This will arise
8057 -- if the current unit and the predicate function are being compiled
8058 -- with validity checks enabled.
8059
8060 elsif Present (Predicate_Function (Typ))
8061 and then Current_Scope = Predicate_Function (Typ)
8062 then
8063 return;
8064
8065 -- If the expression is a packed component of a modular type of the
8066 -- right size, the data is always valid.
8067
8068 elsif Nkind (Expr) = N_Selected_Component
8069 and then Present (Component_Clause (Entity (Selector_Name (Expr))))
8070 and then Is_Modular_Integer_Type (Typ)
8071 and then Modulus (Typ) = 2 ** Esize (Entity (Selector_Name (Expr)))
8072 then
8073 return;
8074
8075 -- Do not generate a validity check when inside a generic unit as this
8076 -- is an expansion activity.
8077
8078 elsif Inside_A_Generic then
8079 return;
8080 end if;
8081
8082 -- Entities declared in Lock_free protected types must be treated as
8083 -- volatile, and we must inhibit validity checks to prevent improper
8084 -- constant folding.
8085
8086 if Is_Entity_Name (Expr)
8087 and then Is_Subprogram (Scope (Entity (Expr)))
8088 and then Present (Protected_Subprogram (Scope (Entity (Expr))))
8089 and then Uses_Lock_Free
8090 (Scope (Protected_Subprogram (Scope (Entity (Expr)))))
8091 then
8092 return;
8093 end if;
8094
8095 -- If we have a checked conversion, then validity check applies to
8096 -- the expression inside the conversion, not the result, since if
8097 -- the expression inside is valid, then so is the conversion result.
8098
8099 Exp := Expr;
8100 while Nkind (Exp) = N_Type_Conversion loop
8101 Exp := Expression (Exp);
8102 end loop;
8103
8104 -- Do not generate a check for a variable which already validates the
8105 -- value of an assignable object.
8106
8107 if Is_Validation_Variable_Reference (Exp) then
8108 return;
8109 end if;
8110
8111 declare
8112 CE : Node_Id;
8113 PV : Node_Id;
8114 Var_Id : Entity_Id;
8115
8116 begin
8117 -- If the expression denotes an assignable object, capture its value
8118 -- in a variable and replace the original expression by the variable.
8119 -- This approach has several effects:
8120
8121 -- 1) The evaluation of the object results in only one read in the
8122 -- case where the object is atomic or volatile.
8123
8124 -- Var ... := Object; -- read
8125
8126 -- 2) The captured value is the one verified by attribute 'Valid.
8127 -- As a result the object is not evaluated again, which would
8128 -- result in an unwanted read in the case where the object is
8129 -- atomic or volatile.
8130
8131 -- if not Var'Valid then -- OK, no read of Object
8132
8133 -- if not Object'Valid then -- Wrong, extra read of Object
8134
8135 -- 3) The captured value replaces the original object reference.
8136 -- As a result the object is not evaluated again, in the same
8137 -- vein as 2).
8138
8139 -- ... Var ... -- OK, no read of Object
8140
8141 -- ... Object ... -- Wrong, extra read of Object
8142
8143 -- 4) The use of a variable to capture the value of the object
8144 -- allows the propagation of any changes back to the original
8145 -- object.
8146
8147 -- procedure Call (Val : in out ...);
8148
8149 -- Var : ... := Object; -- read Object
8150 -- if not Var'Valid then -- validity check
8151 -- Call (Var); -- modify Var
8152 -- Object := Var; -- update Object
8153
8154 if Is_Variable (Exp) then
8155 Var_Id := Make_Temporary (Loc, 'T', Exp);
8156
8157 -- Because we could be dealing with a transient scope which would
8158 -- cause our object declaration to remain unanalyzed we must do
8159 -- some manual decoration.
8160
8161 Set_Ekind (Var_Id, E_Variable);
8162 Set_Etype (Var_Id, Typ);
8163
8164 Insert_Action (Exp,
8165 Make_Object_Declaration (Loc,
8166 Defining_Identifier => Var_Id,
8167 Object_Definition => New_Occurrence_Of (Typ, Loc),
8168 Expression => New_Copy_Tree (Exp)),
8169 Suppress => Validity_Check);
8170
8171 Set_Validated_Object (Var_Id, New_Copy_Tree (Exp));
8172
8173 Rewrite (Exp, New_Occurrence_Of (Var_Id, Loc));
8174
8175 -- Move the Do_Range_Check flag over to the new Exp so it doesn't
8176 -- get lost and doesn't leak elsewhere.
8177
8178 if Do_Range_Check (Validated_Object (Var_Id)) then
8179 Set_Do_Range_Check (Exp);
8180 Set_Do_Range_Check (Validated_Object (Var_Id), False);
8181 end if;
8182
8183 PV := New_Occurrence_Of (Var_Id, Loc);
8184
8185 -- Otherwise the expression does not denote a variable. Force its
8186 -- evaluation by capturing its value in a constant. Generate:
8187
8188 -- Temp : constant ... := Exp;
8189
8190 else
8191 Force_Evaluation
8192 (Exp => Exp,
8193 Related_Id => Related_Id,
8194 Is_Low_Bound => Is_Low_Bound,
8195 Is_High_Bound => Is_High_Bound);
8196
8197 PV := New_Copy_Tree (Exp);
8198 end if;
8199
8200 -- A rather specialized test. If PV is an analyzed expression which
8201 -- is an indexed component of a packed array that has not been
8202 -- properly expanded, turn off its Analyzed flag to make sure it
8203 -- gets properly reexpanded. If the prefix is an access value,
8204 -- the dereference will be added later.
8205
8206 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
8207 -- an analyze with the old parent pointer. This may point e.g. to
8208 -- a subprogram call, which deactivates this expansion.
8209
8210 if Analyzed (PV)
8211 and then Nkind (PV) = N_Indexed_Component
8212 and then Is_Array_Type (Etype (Prefix (PV)))
8213 and then Present (Packed_Array_Impl_Type (Etype (Prefix (PV))))
8214 then
8215 Set_Analyzed (PV, False);
8216 end if;
8217
8218 -- Build the raise CE node to check for validity. We build a type
8219 -- qualification for the prefix, since it may not be of the form of
8220 -- a name, and we don't care in this context!
8221
8222 CE :=
8223 Make_Raise_Constraint_Error (Loc,
8224 Condition =>
8225 Make_Op_Not (Loc,
8226 Right_Opnd =>
8227 Make_Attribute_Reference (Loc,
8228 Prefix => PV,
8229 Attribute_Name => Name_Valid)),
8230 Reason => CE_Invalid_Data);
8231
8232 -- Insert the validity check. Note that we do this with validity
8233 -- checks turned off, to avoid recursion, we do not want validity
8234 -- checks on the validity checking code itself.
8235
8236 Insert_Action (Expr, CE, Suppress => Validity_Check);
8237
8238 -- If the expression is a reference to an element of a bit-packed
8239 -- array, then it is rewritten as a renaming declaration. If the
8240 -- expression is an actual in a call, it has not been expanded,
8241 -- waiting for the proper point at which to do it. The same happens
8242 -- with renamings, so that we have to force the expansion now. This
8243 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
8244 -- and exp_ch6.adb.
8245
8246 if Is_Entity_Name (Exp)
8247 and then Nkind (Parent (Entity (Exp))) =
8248 N_Object_Renaming_Declaration
8249 then
8250 declare
8251 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
8252 begin
8253 if Nkind (Old_Exp) = N_Indexed_Component
8254 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
8255 then
8256 Expand_Packed_Element_Reference (Old_Exp);
8257 end if;
8258 end;
8259 end if;
8260 end;
8261 end Insert_Valid_Check;
8262
8263 -------------------------------------
8264 -- Is_Signed_Integer_Arithmetic_Op --
8265 -------------------------------------
8266
8267 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean is
8268 begin
8269 case Nkind (N) is
8270 when N_Op_Abs
8271 | N_Op_Add
8272 | N_Op_Divide
8273 | N_Op_Expon
8274 | N_Op_Minus
8275 | N_Op_Mod
8276 | N_Op_Multiply
8277 | N_Op_Plus
8278 | N_Op_Rem
8279 | N_Op_Subtract
8280 =>
8281 return Is_Signed_Integer_Type (Etype (N));
8282
8283 when N_Case_Expression
8284 | N_If_Expression
8285 =>
8286 return Is_Signed_Integer_Type (Etype (N));
8287
8288 when others =>
8289 return False;
8290 end case;
8291 end Is_Signed_Integer_Arithmetic_Op;
8292
8293 ----------------------------------
8294 -- Install_Null_Excluding_Check --
8295 ----------------------------------
8296
8297 procedure Install_Null_Excluding_Check (N : Node_Id) is
8298 Loc : constant Source_Ptr := Sloc (Parent (N));
8299 Typ : constant Entity_Id := Etype (N);
8300
8301 function Safe_To_Capture_In_Parameter_Value return Boolean;
8302 -- Determines if it is safe to capture Known_Non_Null status for an
8303 -- the entity referenced by node N. The caller ensures that N is indeed
8304 -- an entity name. It is safe to capture the non-null status for an IN
8305 -- parameter when the reference occurs within a declaration that is sure
8306 -- to be executed as part of the declarative region.
8307
8308 procedure Mark_Non_Null;
8309 -- After installation of check, if the node in question is an entity
8310 -- name, then mark this entity as non-null if possible.
8311
8312 function Safe_To_Capture_In_Parameter_Value return Boolean is
8313 E : constant Entity_Id := Entity (N);
8314 S : constant Entity_Id := Current_Scope;
8315 S_Par : Node_Id;
8316
8317 begin
8318 if Ekind (E) /= E_In_Parameter then
8319 return False;
8320 end if;
8321
8322 -- Two initial context checks. We must be inside a subprogram body
8323 -- with declarations and reference must not appear in nested scopes.
8324
8325 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
8326 or else Scope (E) /= S
8327 then
8328 return False;
8329 end if;
8330
8331 S_Par := Parent (Parent (S));
8332
8333 if Nkind (S_Par) /= N_Subprogram_Body
8334 or else No (Declarations (S_Par))
8335 then
8336 return False;
8337 end if;
8338
8339 declare
8340 N_Decl : Node_Id;
8341 P : Node_Id;
8342
8343 begin
8344 -- Retrieve the declaration node of N (if any). Note that N
8345 -- may be a part of a complex initialization expression.
8346
8347 P := Parent (N);
8348 N_Decl := Empty;
8349 while Present (P) loop
8350
8351 -- If we have a short circuit form, and we are within the right
8352 -- hand expression, we return false, since the right hand side
8353 -- is not guaranteed to be elaborated.
8354
8355 if Nkind (P) in N_Short_Circuit
8356 and then N = Right_Opnd (P)
8357 then
8358 return False;
8359 end if;
8360
8361 -- Similarly, if we are in an if expression and not part of the
8362 -- condition, then we return False, since neither the THEN or
8363 -- ELSE dependent expressions will always be elaborated.
8364
8365 if Nkind (P) = N_If_Expression
8366 and then N /= First (Expressions (P))
8367 then
8368 return False;
8369 end if;
8370
8371 -- If within a case expression, and not part of the expression,
8372 -- then return False, since a particular dependent expression
8373 -- may not always be elaborated
8374
8375 if Nkind (P) = N_Case_Expression
8376 and then N /= Expression (P)
8377 then
8378 return False;
8379 end if;
8380
8381 -- While traversing the parent chain, if node N belongs to a
8382 -- statement, then it may never appear in a declarative region.
8383
8384 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
8385 or else Nkind (P) = N_Procedure_Call_Statement
8386 then
8387 return False;
8388 end if;
8389
8390 -- If we are at a declaration, record it and exit
8391
8392 if Nkind (P) in N_Declaration
8393 and then Nkind (P) not in N_Subprogram_Specification
8394 then
8395 N_Decl := P;
8396 exit;
8397 end if;
8398
8399 P := Parent (P);
8400 end loop;
8401
8402 if No (N_Decl) then
8403 return False;
8404 end if;
8405
8406 return List_Containing (N_Decl) = Declarations (S_Par);
8407 end;
8408 end Safe_To_Capture_In_Parameter_Value;
8409
8410 -------------------
8411 -- Mark_Non_Null --
8412 -------------------
8413
8414 procedure Mark_Non_Null is
8415 begin
8416 -- Only case of interest is if node N is an entity name
8417
8418 if Is_Entity_Name (N) then
8419
8420 -- For sure, we want to clear an indication that this is known to
8421 -- be null, since if we get past this check, it definitely is not.
8422
8423 Set_Is_Known_Null (Entity (N), False);
8424
8425 -- We can mark the entity as known to be non-null if either it is
8426 -- safe to capture the value, or in the case of an IN parameter,
8427 -- which is a constant, if the check we just installed is in the
8428 -- declarative region of the subprogram body. In this latter case,
8429 -- a check is decisive for the rest of the body if the expression
8430 -- is sure to be elaborated, since we know we have to elaborate
8431 -- all declarations before executing the body.
8432
8433 -- Couldn't this always be part of Safe_To_Capture_Value ???
8434
8435 if Safe_To_Capture_Value (N, Entity (N))
8436 or else Safe_To_Capture_In_Parameter_Value
8437 then
8438 Set_Is_Known_Non_Null (Entity (N));
8439 end if;
8440 end if;
8441 end Mark_Non_Null;
8442
8443 -- Start of processing for Install_Null_Excluding_Check
8444
8445 begin
8446 -- No need to add null-excluding checks when the tree may not be fully
8447 -- decorated.
8448
8449 if Serious_Errors_Detected > 0 then
8450 return;
8451 end if;
8452
8453 pragma Assert (Is_Access_Type (Typ));
8454
8455 -- No check inside a generic, check will be emitted in instance
8456
8457 if Inside_A_Generic then
8458 return;
8459 end if;
8460
8461 -- No check needed if known to be non-null
8462
8463 if Known_Non_Null (N) then
8464 return;
8465 end if;
8466
8467 -- If known to be null, here is where we generate a compile time check
8468
8469 if Known_Null (N) then
8470
8471 -- Avoid generating warning message inside init procs. In SPARK mode
8472 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
8473 -- since it will be turned into an error in any case.
8474
8475 if (not Inside_Init_Proc or else SPARK_Mode = On)
8476
8477 -- Do not emit the warning within a conditional expression,
8478 -- where the expression might not be evaluated, and the warning
8479 -- appear as extraneous noise.
8480
8481 and then not Within_Case_Or_If_Expression (N)
8482 then
8483 Apply_Compile_Time_Constraint_Error
8484 (N, "null value not allowed here??", CE_Access_Check_Failed);
8485
8486 -- Remaining cases, where we silently insert the raise
8487
8488 else
8489 Insert_Action (N,
8490 Make_Raise_Constraint_Error (Loc,
8491 Reason => CE_Access_Check_Failed));
8492 end if;
8493
8494 Mark_Non_Null;
8495 return;
8496 end if;
8497
8498 -- If entity is never assigned, for sure a warning is appropriate
8499
8500 if Is_Entity_Name (N) then
8501 Check_Unset_Reference (N);
8502 end if;
8503
8504 -- No check needed if checks are suppressed on the range. Note that we
8505 -- don't set Is_Known_Non_Null in this case (we could legitimately do
8506 -- so, since the program is erroneous, but we don't like to casually
8507 -- propagate such conclusions from erroneosity).
8508
8509 if Access_Checks_Suppressed (Typ) then
8510 return;
8511 end if;
8512
8513 -- No check needed for access to concurrent record types generated by
8514 -- the expander. This is not just an optimization (though it does indeed
8515 -- remove junk checks). It also avoids generation of junk warnings.
8516
8517 if Nkind (N) in N_Has_Chars
8518 and then Chars (N) = Name_uObject
8519 and then Is_Concurrent_Record_Type
8520 (Directly_Designated_Type (Etype (N)))
8521 then
8522 return;
8523 end if;
8524
8525 -- No check needed in interface thunks since the runtime check is
8526 -- already performed at the caller side.
8527
8528 if Is_Thunk (Current_Scope) then
8529 return;
8530 end if;
8531
8532 -- In GNATprove mode, we do not apply the check
8533
8534 if GNATprove_Mode then
8535 return;
8536 end if;
8537
8538 -- Otherwise install access check
8539
8540 Insert_Action (N,
8541 Make_Raise_Constraint_Error (Loc,
8542 Condition =>
8543 Make_Op_Eq (Loc,
8544 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
8545 Right_Opnd => Make_Null (Loc)),
8546 Reason => CE_Access_Check_Failed));
8547
8548 Mark_Non_Null;
8549 end Install_Null_Excluding_Check;
8550
8551 -----------------------------------------
8552 -- Install_Primitive_Elaboration_Check --
8553 -----------------------------------------
8554
8555 procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id) is
8556 function Within_Compilation_Unit_Instance
8557 (Subp_Id : Entity_Id) return Boolean;
8558 -- Determine whether subprogram Subp_Id appears within an instance which
8559 -- acts as a compilation unit.
8560
8561 --------------------------------------
8562 -- Within_Compilation_Unit_Instance --
8563 --------------------------------------
8564
8565 function Within_Compilation_Unit_Instance
8566 (Subp_Id : Entity_Id) return Boolean
8567 is
8568 Pack : Entity_Id;
8569
8570 begin
8571 -- Examine the scope chain looking for a compilation-unit-level
8572 -- instance.
8573
8574 Pack := Scope (Subp_Id);
8575 while Present (Pack) and then Pack /= Standard_Standard loop
8576 if Ekind (Pack) = E_Package
8577 and then Is_Generic_Instance (Pack)
8578 and then Nkind (Parent (Unit_Declaration_Node (Pack))) =
8579 N_Compilation_Unit
8580 then
8581 return True;
8582 end if;
8583
8584 Pack := Scope (Pack);
8585 end loop;
8586
8587 return False;
8588 end Within_Compilation_Unit_Instance;
8589
8590 -- Local declarations
8591
8592 Context : constant Node_Id := Parent (Subp_Body);
8593 Loc : constant Source_Ptr := Sloc (Subp_Body);
8594 Subp_Id : constant Entity_Id := Unique_Defining_Entity (Subp_Body);
8595 Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
8596
8597 Decls : List_Id;
8598 Flag_Id : Entity_Id;
8599 Set_Ins : Node_Id;
8600 Set_Stmt : Node_Id;
8601 Tag_Typ : Entity_Id;
8602
8603 -- Start of processing for Install_Primitive_Elaboration_Check
8604
8605 begin
8606 -- Do not generate an elaboration check in compilation modes where
8607 -- expansion is not desirable.
8608
8609 if GNATprove_Mode then
8610 return;
8611
8612 -- Do not generate an elaboration check if all checks have been
8613 -- suppressed.
8614
8615 elsif Suppress_Checks then
8616 return;
8617
8618 -- Do not generate an elaboration check if the related subprogram is
8619 -- not subjected to accessibility checks.
8620
8621 elsif Elaboration_Checks_Suppressed (Subp_Id) then
8622 return;
8623
8624 -- Do not generate an elaboration check if such code is not desirable
8625
8626 elsif Restriction_Active (No_Elaboration_Code) then
8627 return;
8628
8629 -- Do not generate an elaboration check if exceptions cannot be used,
8630 -- caught, or propagated.
8631
8632 elsif not Exceptions_OK then
8633 return;
8634
8635 -- Do not consider subprograms which act as compilation units, because
8636 -- they cannot be the target of a dispatching call.
8637
8638 elsif Nkind (Context) = N_Compilation_Unit then
8639 return;
8640
8641 -- Do not consider anything other than nonabstract library-level source
8642 -- primitives.
8643
8644 elsif not
8645 (Comes_From_Source (Subp_Id)
8646 and then Is_Library_Level_Entity (Subp_Id)
8647 and then Is_Primitive (Subp_Id)
8648 and then not Is_Abstract_Subprogram (Subp_Id))
8649 then
8650 return;
8651
8652 -- Do not consider inlined primitives, because once the body is inlined
8653 -- the reference to the elaboration flag will be out of place and will
8654 -- result in an undefined symbol.
8655
8656 elsif Is_Inlined (Subp_Id) or else Has_Pragma_Inline (Subp_Id) then
8657 return;
8658
8659 -- Do not generate a duplicate elaboration check. This happens only in
8660 -- the case of primitives completed by an expression function, as the
8661 -- corresponding body is apparently analyzed and expanded twice.
8662
8663 elsif Analyzed (Subp_Body) then
8664 return;
8665
8666 -- Do not consider primitives which occur within an instance that acts
8667 -- as a compilation unit. Such an instance defines its spec and body out
8668 -- of order (body is first) within the tree, which causes the reference
8669 -- to the elaboration flag to appear as an undefined symbol.
8670
8671 elsif Within_Compilation_Unit_Instance (Subp_Id) then
8672 return;
8673 end if;
8674
8675 Tag_Typ := Find_Dispatching_Type (Subp_Id);
8676
8677 -- Only tagged primitives may be the target of a dispatching call
8678
8679 if No (Tag_Typ) then
8680 return;
8681
8682 -- Do not consider finalization-related primitives, because they may
8683 -- need to be called while elaboration is taking place.
8684
8685 elsif Is_Controlled (Tag_Typ)
8686 and then
8687 Chars (Subp_Id) in Name_Adjust | Name_Finalize | Name_Initialize
8688 then
8689 return;
8690 end if;
8691
8692 -- Create the declaration of the elaboration flag. The name carries a
8693 -- unique counter in case of name overloading.
8694
8695 Flag_Id :=
8696 Make_Defining_Identifier (Loc,
8697 Chars => New_External_Name (Chars (Subp_Id), 'E', -1));
8698 Set_Is_Frozen (Flag_Id);
8699
8700 -- Insert the declaration of the elaboration flag in front of the
8701 -- primitive spec and analyze it in the proper context.
8702
8703 Push_Scope (Scope (Subp_Id));
8704
8705 -- Generate:
8706 -- E : Boolean := False;
8707
8708 Insert_Action (Subp_Decl,
8709 Make_Object_Declaration (Loc,
8710 Defining_Identifier => Flag_Id,
8711 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
8712 Expression => New_Occurrence_Of (Standard_False, Loc)));
8713 Pop_Scope;
8714
8715 -- Prevent the compiler from optimizing the elaboration check by killing
8716 -- the current value of the flag and the associated assignment.
8717
8718 Set_Current_Value (Flag_Id, Empty);
8719 Set_Last_Assignment (Flag_Id, Empty);
8720
8721 -- Add a check at the top of the body declarations to ensure that the
8722 -- elaboration flag has been set.
8723
8724 Decls := Declarations (Subp_Body);
8725
8726 if No (Decls) then
8727 Decls := New_List;
8728 Set_Declarations (Subp_Body, Decls);
8729 end if;
8730
8731 -- Generate:
8732 -- if not F then
8733 -- raise Program_Error with "access before elaboration";
8734 -- end if;
8735
8736 Prepend_To (Decls,
8737 Make_Raise_Program_Error (Loc,
8738 Condition =>
8739 Make_Op_Not (Loc,
8740 Right_Opnd => New_Occurrence_Of (Flag_Id, Loc)),
8741 Reason => PE_Access_Before_Elaboration));
8742
8743 Analyze (First (Decls));
8744
8745 -- Set the elaboration flag once the body has been elaborated. Insert
8746 -- the statement after the subprogram stub when the primitive body is
8747 -- a subunit.
8748
8749 if Nkind (Context) = N_Subunit then
8750 Set_Ins := Corresponding_Stub (Context);
8751 else
8752 Set_Ins := Subp_Body;
8753 end if;
8754
8755 -- Generate:
8756 -- E := True;
8757
8758 Set_Stmt :=
8759 Make_Assignment_Statement (Loc,
8760 Name => New_Occurrence_Of (Flag_Id, Loc),
8761 Expression => New_Occurrence_Of (Standard_True, Loc));
8762
8763 -- Mark the assignment statement as elaboration code. This allows the
8764 -- early call region mechanism (see Sem_Elab) to properly ignore such
8765 -- assignments even though they are non-preelaborable code.
8766
8767 Set_Is_Elaboration_Code (Set_Stmt);
8768
8769 Insert_After_And_Analyze (Set_Ins, Set_Stmt);
8770 end Install_Primitive_Elaboration_Check;
8771
8772 --------------------------
8773 -- Install_Static_Check --
8774 --------------------------
8775
8776 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
8777 Stat : constant Boolean := Is_OK_Static_Expression (R_Cno);
8778 Typ : constant Entity_Id := Etype (R_Cno);
8779
8780 begin
8781 Rewrite (R_Cno,
8782 Make_Raise_Constraint_Error (Loc,
8783 Reason => CE_Range_Check_Failed));
8784 Set_Analyzed (R_Cno);
8785 Set_Etype (R_Cno, Typ);
8786 Set_Raises_Constraint_Error (R_Cno);
8787 Set_Is_Static_Expression (R_Cno, Stat);
8788
8789 -- Now deal with possible local raise handling
8790
8791 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
8792 end Install_Static_Check;
8793
8794 -------------------------
8795 -- Is_Check_Suppressed --
8796 -------------------------
8797
8798 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean is
8799 Ptr : Suppress_Stack_Entry_Ptr;
8800
8801 begin
8802 -- First search the local entity suppress stack. We search this from the
8803 -- top of the stack down so that we get the innermost entry that applies
8804 -- to this case if there are nested entries.
8805
8806 Ptr := Local_Suppress_Stack_Top;
8807 while Ptr /= null loop
8808 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8809 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8810 then
8811 return Ptr.Suppress;
8812 end if;
8813
8814 Ptr := Ptr.Prev;
8815 end loop;
8816
8817 -- Now search the global entity suppress table for a matching entry.
8818 -- We also search this from the top down so that if there are multiple
8819 -- pragmas for the same entity, the last one applies (not clear what
8820 -- or whether the RM specifies this handling, but it seems reasonable).
8821
8822 Ptr := Global_Suppress_Stack_Top;
8823 while Ptr /= null loop
8824 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8825 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8826 then
8827 return Ptr.Suppress;
8828 end if;
8829
8830 Ptr := Ptr.Prev;
8831 end loop;
8832
8833 -- If we did not find a matching entry, then use the normal scope
8834 -- suppress value after all (actually this will be the global setting
8835 -- since it clearly was not overridden at any point). For a predefined
8836 -- check, we test the specific flag. For a user defined check, we check
8837 -- the All_Checks flag. The Overflow flag requires special handling to
8838 -- deal with the General vs Assertion case.
8839
8840 if C = Overflow_Check then
8841 return Overflow_Checks_Suppressed (Empty);
8842
8843 elsif C in Predefined_Check_Id then
8844 return Scope_Suppress.Suppress (C);
8845
8846 else
8847 return Scope_Suppress.Suppress (All_Checks);
8848 end if;
8849 end Is_Check_Suppressed;
8850
8851 ---------------------
8852 -- Kill_All_Checks --
8853 ---------------------
8854
8855 procedure Kill_All_Checks is
8856 begin
8857 if Debug_Flag_CC then
8858 w ("Kill_All_Checks");
8859 end if;
8860
8861 -- We reset the number of saved checks to zero, and also modify all
8862 -- stack entries for statement ranges to indicate that the number of
8863 -- checks at each level is now zero.
8864
8865 Num_Saved_Checks := 0;
8866
8867 -- Note: the Int'Min here avoids any possibility of J being out of
8868 -- range when called from e.g. Conditional_Statements_Begin.
8869
8870 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
8871 Saved_Checks_Stack (J) := 0;
8872 end loop;
8873 end Kill_All_Checks;
8874
8875 -----------------
8876 -- Kill_Checks --
8877 -----------------
8878
8879 procedure Kill_Checks (V : Entity_Id) is
8880 begin
8881 if Debug_Flag_CC then
8882 w ("Kill_Checks for entity", Int (V));
8883 end if;
8884
8885 for J in 1 .. Num_Saved_Checks loop
8886 if Saved_Checks (J).Entity = V then
8887 if Debug_Flag_CC then
8888 w (" Checks killed for saved check ", J);
8889 end if;
8890
8891 Saved_Checks (J).Killed := True;
8892 end if;
8893 end loop;
8894 end Kill_Checks;
8895
8896 ------------------------------
8897 -- Length_Checks_Suppressed --
8898 ------------------------------
8899
8900 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
8901 begin
8902 if Present (E) and then Checks_May_Be_Suppressed (E) then
8903 return Is_Check_Suppressed (E, Length_Check);
8904 else
8905 return Scope_Suppress.Suppress (Length_Check);
8906 end if;
8907 end Length_Checks_Suppressed;
8908
8909 -----------------------
8910 -- Make_Bignum_Block --
8911 -----------------------
8912
8913 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id is
8914 M : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uM);
8915 begin
8916 return
8917 Make_Block_Statement (Loc,
8918 Declarations =>
8919 New_List (Build_SS_Mark_Call (Loc, M)),
8920 Handled_Statement_Sequence =>
8921 Make_Handled_Sequence_Of_Statements (Loc,
8922 Statements => New_List (Build_SS_Release_Call (Loc, M))));
8923 end Make_Bignum_Block;
8924
8925 ----------------------------------
8926 -- Minimize_Eliminate_Overflows --
8927 ----------------------------------
8928
8929 -- This is a recursive routine that is called at the top of an expression
8930 -- tree to properly process overflow checking for a whole subtree by making
8931 -- recursive calls to process operands. This processing may involve the use
8932 -- of bignum or long long integer arithmetic, which will change the types
8933 -- of operands and results. That's why we can't do this bottom up (since
8934 -- it would interfere with semantic analysis).
8935
8936 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
8937 -- the operator expansion routines, as well as the expansion routines for
8938 -- if/case expression, do nothing (for the moment) except call the routine
8939 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8940 -- routine does nothing for non top-level nodes, so at the point where the
8941 -- call is made for the top level node, the entire expression subtree has
8942 -- not been expanded, or processed for overflow. All that has to happen as
8943 -- a result of the top level call to this routine.
8944
8945 -- As noted above, the overflow processing works by making recursive calls
8946 -- for the operands, and figuring out what to do, based on the processing
8947 -- of these operands (e.g. if a bignum operand appears, the parent op has
8948 -- to be done in bignum mode), and the determined ranges of the operands.
8949
8950 -- After possible rewriting of a constituent subexpression node, a call is
8951 -- made to either reexpand the node (if nothing has changed) or reanalyze
8952 -- the node (if it has been modified by the overflow check processing). The
8953 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8954 -- a recursive call into the whole overflow apparatus, an important rule
8955 -- for this call is that the overflow handling mode must be temporarily set
8956 -- to STRICT.
8957
8958 procedure Minimize_Eliminate_Overflows
8959 (N : Node_Id;
8960 Lo : out Uint;
8961 Hi : out Uint;
8962 Top_Level : Boolean)
8963 is
8964 Rtyp : constant Entity_Id := Etype (N);
8965 pragma Assert (Is_Signed_Integer_Type (Rtyp));
8966 -- Result type, must be a signed integer type
8967
8968 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
8969 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
8970
8971 Loc : constant Source_Ptr := Sloc (N);
8972
8973 Rlo, Rhi : Uint;
8974 -- Ranges of values for right operand (operator case)
8975
8976 Llo : Uint := No_Uint; -- initialize to prevent warning
8977 Lhi : Uint := No_Uint; -- initialize to prevent warning
8978 -- Ranges of values for left operand (operator case)
8979
8980 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
8981 -- Operands and results are of this type when we convert
8982
8983 LLLo : constant Uint := Intval (Type_Low_Bound (LLIB));
8984 LLHi : constant Uint := Intval (Type_High_Bound (LLIB));
8985 -- Bounds of Long_Long_Integer
8986
8987 Binary : constant Boolean := Nkind (N) in N_Binary_Op;
8988 -- Indicates binary operator case
8989
8990 OK : Boolean;
8991 -- Used in call to Determine_Range
8992
8993 Bignum_Operands : Boolean;
8994 -- Set True if one or more operands is already of type Bignum, meaning
8995 -- that for sure (regardless of Top_Level setting) we are committed to
8996 -- doing the operation in Bignum mode (or in the case of a case or if
8997 -- expression, converting all the dependent expressions to Bignum).
8998
8999 Long_Long_Integer_Operands : Boolean;
9000 -- Set True if one or more operands is already of type Long_Long_Integer
9001 -- which means that if the result is known to be in the result type
9002 -- range, then we must convert such operands back to the result type.
9003
9004 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False);
9005 -- This is called when we have modified the node and we therefore need
9006 -- to reanalyze it. It is important that we reset the mode to STRICT for
9007 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
9008 -- we would reenter this routine recursively which would not be good.
9009 -- The argument Suppress is set True if we also want to suppress
9010 -- overflow checking for the reexpansion (this is set when we know
9011 -- overflow is not possible). Typ is the type for the reanalysis.
9012
9013 procedure Reexpand (Suppress : Boolean := False);
9014 -- This is like Reanalyze, but does not do the Analyze step, it only
9015 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
9016 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
9017 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
9018 -- Note that skipping reanalysis is not just an optimization, testing
9019 -- has showed up several complex cases in which reanalyzing an already
9020 -- analyzed node causes incorrect behavior.
9021
9022 function In_Result_Range return Boolean;
9023 -- Returns True iff Lo .. Hi are within range of the result type
9024
9025 procedure Max (A : in out Uint; B : Uint);
9026 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
9027
9028 procedure Min (A : in out Uint; B : Uint);
9029 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
9030
9031 ---------------------
9032 -- In_Result_Range --
9033 ---------------------
9034
9035 function In_Result_Range return Boolean is
9036 begin
9037 if Lo = No_Uint or else Hi = No_Uint then
9038 return False;
9039
9040 elsif Is_OK_Static_Subtype (Etype (N)) then
9041 return Lo >= Expr_Value (Type_Low_Bound (Rtyp))
9042 and then
9043 Hi <= Expr_Value (Type_High_Bound (Rtyp));
9044
9045 else
9046 return Lo >= Expr_Value (Type_Low_Bound (Base_Type (Rtyp)))
9047 and then
9048 Hi <= Expr_Value (Type_High_Bound (Base_Type (Rtyp)));
9049 end if;
9050 end In_Result_Range;
9051
9052 ---------
9053 -- Max --
9054 ---------
9055
9056 procedure Max (A : in out Uint; B : Uint) is
9057 begin
9058 if A = No_Uint or else B > A then
9059 A := B;
9060 end if;
9061 end Max;
9062
9063 ---------
9064 -- Min --
9065 ---------
9066
9067 procedure Min (A : in out Uint; B : Uint) is
9068 begin
9069 if A = No_Uint or else B < A then
9070 A := B;
9071 end if;
9072 end Min;
9073
9074 ---------------
9075 -- Reanalyze --
9076 ---------------
9077
9078 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False) is
9079 Svg : constant Overflow_Mode_Type :=
9080 Scope_Suppress.Overflow_Mode_General;
9081 Sva : constant Overflow_Mode_Type :=
9082 Scope_Suppress.Overflow_Mode_Assertions;
9083 Svo : constant Boolean :=
9084 Scope_Suppress.Suppress (Overflow_Check);
9085
9086 begin
9087 Scope_Suppress.Overflow_Mode_General := Strict;
9088 Scope_Suppress.Overflow_Mode_Assertions := Strict;
9089
9090 if Suppress then
9091 Scope_Suppress.Suppress (Overflow_Check) := True;
9092 end if;
9093
9094 Analyze_And_Resolve (N, Typ);
9095
9096 Scope_Suppress.Suppress (Overflow_Check) := Svo;
9097 Scope_Suppress.Overflow_Mode_General := Svg;
9098 Scope_Suppress.Overflow_Mode_Assertions := Sva;
9099 end Reanalyze;
9100
9101 --------------
9102 -- Reexpand --
9103 --------------
9104
9105 procedure Reexpand (Suppress : Boolean := False) is
9106 Svg : constant Overflow_Mode_Type :=
9107 Scope_Suppress.Overflow_Mode_General;
9108 Sva : constant Overflow_Mode_Type :=
9109 Scope_Suppress.Overflow_Mode_Assertions;
9110 Svo : constant Boolean :=
9111 Scope_Suppress.Suppress (Overflow_Check);
9112
9113 begin
9114 Scope_Suppress.Overflow_Mode_General := Strict;
9115 Scope_Suppress.Overflow_Mode_Assertions := Strict;
9116 Set_Analyzed (N, False);
9117
9118 if Suppress then
9119 Scope_Suppress.Suppress (Overflow_Check) := True;
9120 end if;
9121
9122 Expand (N);
9123
9124 Scope_Suppress.Suppress (Overflow_Check) := Svo;
9125 Scope_Suppress.Overflow_Mode_General := Svg;
9126 Scope_Suppress.Overflow_Mode_Assertions := Sva;
9127 end Reexpand;
9128
9129 -- Start of processing for Minimize_Eliminate_Overflows
9130
9131 begin
9132 -- Default initialize Lo and Hi since these are not guaranteed to be
9133 -- set otherwise.
9134
9135 Lo := No_Uint;
9136 Hi := No_Uint;
9137
9138 -- Case where we do not have a signed integer arithmetic operation
9139
9140 if not Is_Signed_Integer_Arithmetic_Op (N) then
9141
9142 -- Use the normal Determine_Range routine to get the range. We
9143 -- don't require operands to be valid, invalid values may result in
9144 -- rubbish results where the result has not been properly checked for
9145 -- overflow, that's fine.
9146
9147 Determine_Range (N, OK, Lo, Hi, Assume_Valid => False);
9148
9149 -- If Determine_Range did not work (can this in fact happen? Not
9150 -- clear but might as well protect), use type bounds.
9151
9152 if not OK then
9153 Lo := Intval (Type_Low_Bound (Base_Type (Etype (N))));
9154 Hi := Intval (Type_High_Bound (Base_Type (Etype (N))));
9155 end if;
9156
9157 -- If we don't have a binary operator, all we have to do is to set
9158 -- the Hi/Lo range, so we are done.
9159
9160 return;
9161
9162 -- Processing for if expression
9163
9164 elsif Nkind (N) = N_If_Expression then
9165 declare
9166 Then_DE : constant Node_Id := Next (First (Expressions (N)));
9167 Else_DE : constant Node_Id := Next (Then_DE);
9168
9169 begin
9170 Bignum_Operands := False;
9171
9172 Minimize_Eliminate_Overflows
9173 (Then_DE, Lo, Hi, Top_Level => False);
9174
9175 if Lo = No_Uint then
9176 Bignum_Operands := True;
9177 end if;
9178
9179 Minimize_Eliminate_Overflows
9180 (Else_DE, Rlo, Rhi, Top_Level => False);
9181
9182 if Rlo = No_Uint then
9183 Bignum_Operands := True;
9184 else
9185 Long_Long_Integer_Operands :=
9186 Etype (Then_DE) = LLIB or else Etype (Else_DE) = LLIB;
9187
9188 Min (Lo, Rlo);
9189 Max (Hi, Rhi);
9190 end if;
9191
9192 -- If at least one of our operands is now Bignum, we must rebuild
9193 -- the if expression to use Bignum operands. We will analyze the
9194 -- rebuilt if expression with overflow checks off, since once we
9195 -- are in bignum mode, we are all done with overflow checks.
9196
9197 if Bignum_Operands then
9198 Rewrite (N,
9199 Make_If_Expression (Loc,
9200 Expressions => New_List (
9201 Remove_Head (Expressions (N)),
9202 Convert_To_Bignum (Then_DE),
9203 Convert_To_Bignum (Else_DE)),
9204 Is_Elsif => Is_Elsif (N)));
9205
9206 Reanalyze (RTE (RE_Bignum), Suppress => True);
9207
9208 -- If we have no Long_Long_Integer operands, then we are in result
9209 -- range, since it means that none of our operands felt the need
9210 -- to worry about overflow (otherwise it would have already been
9211 -- converted to long long integer or bignum). We reexpand to
9212 -- complete the expansion of the if expression (but we do not
9213 -- need to reanalyze).
9214
9215 elsif not Long_Long_Integer_Operands then
9216 Set_Do_Overflow_Check (N, False);
9217 Reexpand;
9218
9219 -- Otherwise convert us to long long integer mode. Note that we
9220 -- don't need any further overflow checking at this level.
9221
9222 else
9223 Convert_To_And_Rewrite (LLIB, Then_DE);
9224 Convert_To_And_Rewrite (LLIB, Else_DE);
9225 Set_Etype (N, LLIB);
9226
9227 -- Now reanalyze with overflow checks off
9228
9229 Set_Do_Overflow_Check (N, False);
9230 Reanalyze (LLIB, Suppress => True);
9231 end if;
9232 end;
9233
9234 return;
9235
9236 -- Here for case expression
9237
9238 elsif Nkind (N) = N_Case_Expression then
9239 Bignum_Operands := False;
9240 Long_Long_Integer_Operands := False;
9241
9242 declare
9243 Alt : Node_Id;
9244
9245 begin
9246 -- Loop through expressions applying recursive call
9247
9248 Alt := First (Alternatives (N));
9249 while Present (Alt) loop
9250 declare
9251 Aexp : constant Node_Id := Expression (Alt);
9252
9253 begin
9254 Minimize_Eliminate_Overflows
9255 (Aexp, Lo, Hi, Top_Level => False);
9256
9257 if Lo = No_Uint then
9258 Bignum_Operands := True;
9259 elsif Etype (Aexp) = LLIB then
9260 Long_Long_Integer_Operands := True;
9261 end if;
9262 end;
9263
9264 Next (Alt);
9265 end loop;
9266
9267 -- If we have no bignum or long long integer operands, it means
9268 -- that none of our dependent expressions could raise overflow.
9269 -- In this case, we simply return with no changes except for
9270 -- resetting the overflow flag, since we are done with overflow
9271 -- checks for this node. We will reexpand to get the needed
9272 -- expansion for the case expression, but we do not need to
9273 -- reanalyze, since nothing has changed.
9274
9275 if not (Bignum_Operands or Long_Long_Integer_Operands) then
9276 Set_Do_Overflow_Check (N, False);
9277 Reexpand (Suppress => True);
9278
9279 -- Otherwise we are going to rebuild the case expression using
9280 -- either bignum or long long integer operands throughout.
9281
9282 else
9283 declare
9284 Rtype : Entity_Id := Empty;
9285 New_Alts : List_Id;
9286 New_Exp : Node_Id;
9287
9288 begin
9289 New_Alts := New_List;
9290 Alt := First (Alternatives (N));
9291 while Present (Alt) loop
9292 if Bignum_Operands then
9293 New_Exp := Convert_To_Bignum (Expression (Alt));
9294 Rtype := RTE (RE_Bignum);
9295 else
9296 New_Exp := Convert_To (LLIB, Expression (Alt));
9297 Rtype := LLIB;
9298 end if;
9299
9300 Append_To (New_Alts,
9301 Make_Case_Expression_Alternative (Sloc (Alt),
9302 Discrete_Choices => Discrete_Choices (Alt),
9303 Expression => New_Exp));
9304
9305 Next (Alt);
9306 end loop;
9307
9308 Rewrite (N,
9309 Make_Case_Expression (Loc,
9310 Expression => Expression (N),
9311 Alternatives => New_Alts));
9312
9313 pragma Assert (Present (Rtype));
9314 Reanalyze (Rtype, Suppress => True);
9315 end;
9316 end if;
9317 end;
9318
9319 return;
9320 end if;
9321
9322 -- If we have an arithmetic operator we make recursive calls on the
9323 -- operands to get the ranges (and to properly process the subtree
9324 -- that lies below us).
9325
9326 Minimize_Eliminate_Overflows
9327 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
9328
9329 if Binary then
9330 Minimize_Eliminate_Overflows
9331 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
9332 end if;
9333
9334 -- Record if we have Long_Long_Integer operands
9335
9336 Long_Long_Integer_Operands :=
9337 Etype (Right_Opnd (N)) = LLIB
9338 or else (Binary and then Etype (Left_Opnd (N)) = LLIB);
9339
9340 -- If either operand is a bignum, then result will be a bignum and we
9341 -- don't need to do any range analysis. As previously discussed we could
9342 -- do range analysis in such cases, but it could mean working with giant
9343 -- numbers at compile time for very little gain (the number of cases
9344 -- in which we could slip back from bignum mode is small).
9345
9346 if Rlo = No_Uint or else (Binary and then Llo = No_Uint) then
9347 Lo := No_Uint;
9348 Hi := No_Uint;
9349 Bignum_Operands := True;
9350
9351 -- Otherwise compute result range
9352
9353 else
9354 Compute_Range_For_Arithmetic_Op
9355 (Nkind (N), Llo, Lhi, Rlo, Rhi, OK, Lo, Hi);
9356 Bignum_Operands := False;
9357 end if;
9358
9359 -- Here for the case where we have not rewritten anything (no bignum
9360 -- operands or long long integer operands), and we know the result.
9361 -- If we know we are in the result range, and we do not have Bignum
9362 -- operands or Long_Long_Integer operands, we can just reexpand with
9363 -- overflow checks turned off (since we know we cannot have overflow).
9364 -- As always the reexpansion is required to complete expansion of the
9365 -- operator, but we do not need to reanalyze, and we prevent recursion
9366 -- by suppressing the check.
9367
9368 if not (Bignum_Operands or Long_Long_Integer_Operands)
9369 and then In_Result_Range
9370 then
9371 Set_Do_Overflow_Check (N, False);
9372 Reexpand (Suppress => True);
9373 return;
9374
9375 -- Here we know that we are not in the result range, and in the general
9376 -- case we will move into either the Bignum or Long_Long_Integer domain
9377 -- to compute the result. However, there is one exception. If we are
9378 -- at the top level, and we do not have Bignum or Long_Long_Integer
9379 -- operands, we will have to immediately convert the result back to
9380 -- the result type, so there is no point in Bignum/Long_Long_Integer
9381 -- fiddling.
9382
9383 elsif Top_Level
9384 and then not (Bignum_Operands or Long_Long_Integer_Operands)
9385
9386 -- One further refinement. If we are at the top level, but our parent
9387 -- is a type conversion, then go into bignum or long long integer node
9388 -- since the result will be converted to that type directly without
9389 -- going through the result type, and we may avoid an overflow. This
9390 -- is the case for example of Long_Long_Integer (A ** 4), where A is
9391 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
9392 -- but does not fit in Integer.
9393
9394 and then Nkind (Parent (N)) /= N_Type_Conversion
9395 then
9396 -- Here keep original types, but we need to complete analysis
9397
9398 -- One subtlety. We can't just go ahead and do an analyze operation
9399 -- here because it will cause recursion into the whole MINIMIZED/
9400 -- ELIMINATED overflow processing which is not what we want. Here
9401 -- we are at the top level, and we need a check against the result
9402 -- mode (i.e. we want to use STRICT mode). So do exactly that.
9403 -- Also, we have not modified the node, so this is a case where
9404 -- we need to reexpand, but not reanalyze.
9405
9406 Reexpand;
9407 return;
9408
9409 -- Cases where we do the operation in Bignum mode. This happens either
9410 -- because one of our operands is in Bignum mode already, or because
9411 -- the computed bounds are outside the bounds of Long_Long_Integer,
9412 -- which in some cases can be indicated by Hi and Lo being No_Uint.
9413
9414 -- Note: we could do better here and in some cases switch back from
9415 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
9416 -- 0 .. 1, but the cases are rare and it is not worth the effort.
9417 -- Failing to do this switching back is only an efficiency issue.
9418
9419 elsif Lo = No_Uint or else Lo < LLLo or else Hi > LLHi then
9420
9421 -- OK, we are definitely outside the range of Long_Long_Integer. The
9422 -- question is whether to move to Bignum mode, or stay in the domain
9423 -- of Long_Long_Integer, signalling that an overflow check is needed.
9424
9425 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
9426 -- the Bignum business. In ELIMINATED mode, we will normally move
9427 -- into Bignum mode, but there is an exception if neither of our
9428 -- operands is Bignum now, and we are at the top level (Top_Level
9429 -- set True). In this case, there is no point in moving into Bignum
9430 -- mode to prevent overflow if the caller will immediately convert
9431 -- the Bignum value back to LLI with an overflow check. It's more
9432 -- efficient to stay in LLI mode with an overflow check (if needed)
9433
9434 if Check_Mode = Minimized
9435 or else (Top_Level and not Bignum_Operands)
9436 then
9437 if Do_Overflow_Check (N) then
9438 Enable_Overflow_Check (N);
9439 end if;
9440
9441 -- The result now has to be in Long_Long_Integer mode, so adjust
9442 -- the possible range to reflect this. Note these calls also
9443 -- change No_Uint values from the top level case to LLI bounds.
9444
9445 Max (Lo, LLLo);
9446 Min (Hi, LLHi);
9447
9448 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
9449
9450 else
9451 pragma Assert (Check_Mode = Eliminated);
9452
9453 declare
9454 Fent : Entity_Id;
9455 Args : List_Id;
9456
9457 begin
9458 case Nkind (N) is
9459 when N_Op_Abs =>
9460 Fent := RTE (RE_Big_Abs);
9461
9462 when N_Op_Add =>
9463 Fent := RTE (RE_Big_Add);
9464
9465 when N_Op_Divide =>
9466 Fent := RTE (RE_Big_Div);
9467
9468 when N_Op_Expon =>
9469 Fent := RTE (RE_Big_Exp);
9470
9471 when N_Op_Minus =>
9472 Fent := RTE (RE_Big_Neg);
9473
9474 when N_Op_Mod =>
9475 Fent := RTE (RE_Big_Mod);
9476
9477 when N_Op_Multiply =>
9478 Fent := RTE (RE_Big_Mul);
9479
9480 when N_Op_Rem =>
9481 Fent := RTE (RE_Big_Rem);
9482
9483 when N_Op_Subtract =>
9484 Fent := RTE (RE_Big_Sub);
9485
9486 -- Anything else is an internal error, this includes the
9487 -- N_Op_Plus case, since how can plus cause the result
9488 -- to be out of range if the operand is in range?
9489
9490 when others =>
9491 raise Program_Error;
9492 end case;
9493
9494 -- Construct argument list for Bignum call, converting our
9495 -- operands to Bignum form if they are not already there.
9496
9497 Args := New_List;
9498
9499 if Binary then
9500 Append_To (Args, Convert_To_Bignum (Left_Opnd (N)));
9501 end if;
9502
9503 Append_To (Args, Convert_To_Bignum (Right_Opnd (N)));
9504
9505 -- Now rewrite the arithmetic operator with a call to the
9506 -- corresponding bignum function.
9507
9508 Rewrite (N,
9509 Make_Function_Call (Loc,
9510 Name => New_Occurrence_Of (Fent, Loc),
9511 Parameter_Associations => Args));
9512 Reanalyze (RTE (RE_Bignum), Suppress => True);
9513
9514 -- Indicate result is Bignum mode
9515
9516 Lo := No_Uint;
9517 Hi := No_Uint;
9518 return;
9519 end;
9520 end if;
9521
9522 -- Otherwise we are in range of Long_Long_Integer, so no overflow
9523 -- check is required, at least not yet.
9524
9525 else
9526 Set_Do_Overflow_Check (N, False);
9527 end if;
9528
9529 -- Here we are not in Bignum territory, but we may have long long
9530 -- integer operands that need special handling. First a special check:
9531 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9532 -- it means we converted it to prevent overflow, but exponentiation
9533 -- requires a Natural right operand, so convert it back to Natural.
9534 -- This conversion may raise an exception which is fine.
9535
9536 if Nkind (N) = N_Op_Expon and then Etype (Right_Opnd (N)) = LLIB then
9537 Convert_To_And_Rewrite (Standard_Natural, Right_Opnd (N));
9538 end if;
9539
9540 -- Here we will do the operation in Long_Long_Integer. We do this even
9541 -- if we know an overflow check is required, better to do this in long
9542 -- long integer mode, since we are less likely to overflow.
9543
9544 -- Convert right or only operand to Long_Long_Integer, except that
9545 -- we do not touch the exponentiation right operand.
9546
9547 if Nkind (N) /= N_Op_Expon then
9548 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
9549 end if;
9550
9551 -- Convert left operand to Long_Long_Integer for binary case
9552
9553 if Binary then
9554 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
9555 end if;
9556
9557 -- Reset node to unanalyzed
9558
9559 Set_Analyzed (N, False);
9560 Set_Etype (N, Empty);
9561 Set_Entity (N, Empty);
9562
9563 -- Now analyze this new node. This reanalysis will complete processing
9564 -- for the node. In particular we will complete the expansion of an
9565 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9566 -- we will complete any division checks (since we have not changed the
9567 -- setting of the Do_Division_Check flag).
9568
9569 -- We do this reanalysis in STRICT mode to avoid recursion into the
9570 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
9571
9572 declare
9573 SG : constant Overflow_Mode_Type :=
9574 Scope_Suppress.Overflow_Mode_General;
9575 SA : constant Overflow_Mode_Type :=
9576 Scope_Suppress.Overflow_Mode_Assertions;
9577
9578 begin
9579 Scope_Suppress.Overflow_Mode_General := Strict;
9580 Scope_Suppress.Overflow_Mode_Assertions := Strict;
9581
9582 if not Do_Overflow_Check (N) then
9583 Reanalyze (LLIB, Suppress => True);
9584 else
9585 Reanalyze (LLIB);
9586 end if;
9587
9588 Scope_Suppress.Overflow_Mode_General := SG;
9589 Scope_Suppress.Overflow_Mode_Assertions := SA;
9590 end;
9591 end Minimize_Eliminate_Overflows;
9592
9593 -------------------------
9594 -- Overflow_Check_Mode --
9595 -------------------------
9596
9597 function Overflow_Check_Mode return Overflow_Mode_Type is
9598 begin
9599 if In_Assertion_Expr = 0 then
9600 return Scope_Suppress.Overflow_Mode_General;
9601 else
9602 return Scope_Suppress.Overflow_Mode_Assertions;
9603 end if;
9604 end Overflow_Check_Mode;
9605
9606 --------------------------------
9607 -- Overflow_Checks_Suppressed --
9608 --------------------------------
9609
9610 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
9611 begin
9612 if Present (E) and then Checks_May_Be_Suppressed (E) then
9613 return Is_Check_Suppressed (E, Overflow_Check);
9614 else
9615 return Scope_Suppress.Suppress (Overflow_Check);
9616 end if;
9617 end Overflow_Checks_Suppressed;
9618
9619 ---------------------------------
9620 -- Predicate_Checks_Suppressed --
9621 ---------------------------------
9622
9623 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean is
9624 begin
9625 if Present (E) and then Checks_May_Be_Suppressed (E) then
9626 return Is_Check_Suppressed (E, Predicate_Check);
9627 else
9628 return Scope_Suppress.Suppress (Predicate_Check);
9629 end if;
9630 end Predicate_Checks_Suppressed;
9631
9632 -----------------------------
9633 -- Range_Checks_Suppressed --
9634 -----------------------------
9635
9636 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
9637 begin
9638 if Present (E) then
9639 if Kill_Range_Checks (E) then
9640 return True;
9641
9642 elsif Checks_May_Be_Suppressed (E) then
9643 return Is_Check_Suppressed (E, Range_Check);
9644 end if;
9645 end if;
9646
9647 return Scope_Suppress.Suppress (Range_Check);
9648 end Range_Checks_Suppressed;
9649
9650 -----------------------------------------
9651 -- Range_Or_Validity_Checks_Suppressed --
9652 -----------------------------------------
9653
9654 -- Note: the coding would be simpler here if we simply made appropriate
9655 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9656 -- duplicated checks which we prefer to avoid.
9657
9658 function Range_Or_Validity_Checks_Suppressed
9659 (Expr : Node_Id) return Boolean
9660 is
9661 begin
9662 -- Immediate return if scope checks suppressed for either check
9663
9664 if Scope_Suppress.Suppress (Range_Check)
9665 or
9666 Scope_Suppress.Suppress (Validity_Check)
9667 then
9668 return True;
9669 end if;
9670
9671 -- If no expression, that's odd, decide that checks are suppressed,
9672 -- since we don't want anyone trying to do checks in this case, which
9673 -- is most likely the result of some other error.
9674
9675 if No (Expr) then
9676 return True;
9677 end if;
9678
9679 -- Expression is present, so perform suppress checks on type
9680
9681 declare
9682 Typ : constant Entity_Id := Etype (Expr);
9683 begin
9684 if Checks_May_Be_Suppressed (Typ)
9685 and then (Is_Check_Suppressed (Typ, Range_Check)
9686 or else
9687 Is_Check_Suppressed (Typ, Validity_Check))
9688 then
9689 return True;
9690 end if;
9691 end;
9692
9693 -- If expression is an entity name, perform checks on this entity
9694
9695 if Is_Entity_Name (Expr) then
9696 declare
9697 Ent : constant Entity_Id := Entity (Expr);
9698 begin
9699 if Checks_May_Be_Suppressed (Ent) then
9700 return Is_Check_Suppressed (Ent, Range_Check)
9701 or else Is_Check_Suppressed (Ent, Validity_Check);
9702 end if;
9703 end;
9704 end if;
9705
9706 -- If we fall through, no checks suppressed
9707
9708 return False;
9709 end Range_Or_Validity_Checks_Suppressed;
9710
9711 -------------------
9712 -- Remove_Checks --
9713 -------------------
9714
9715 procedure Remove_Checks (Expr : Node_Id) is
9716 function Process (N : Node_Id) return Traverse_Result;
9717 -- Process a single node during the traversal
9718
9719 procedure Traverse is new Traverse_Proc (Process);
9720 -- The traversal procedure itself
9721
9722 -------------
9723 -- Process --
9724 -------------
9725
9726 function Process (N : Node_Id) return Traverse_Result is
9727 begin
9728 if Nkind (N) not in N_Subexpr then
9729 return Skip;
9730 end if;
9731
9732 Set_Do_Range_Check (N, False);
9733
9734 case Nkind (N) is
9735 when N_And_Then =>
9736 Traverse (Left_Opnd (N));
9737 return Skip;
9738
9739 when N_Attribute_Reference =>
9740 Set_Do_Overflow_Check (N, False);
9741
9742 when N_Function_Call =>
9743 Set_Do_Tag_Check (N, False);
9744
9745 when N_Op =>
9746 Set_Do_Overflow_Check (N, False);
9747
9748 case Nkind (N) is
9749 when N_Op_Divide =>
9750 Set_Do_Division_Check (N, False);
9751
9752 when N_Op_And =>
9753 Set_Do_Length_Check (N, False);
9754
9755 when N_Op_Mod =>
9756 Set_Do_Division_Check (N, False);
9757
9758 when N_Op_Or =>
9759 Set_Do_Length_Check (N, False);
9760
9761 when N_Op_Rem =>
9762 Set_Do_Division_Check (N, False);
9763
9764 when N_Op_Xor =>
9765 Set_Do_Length_Check (N, False);
9766
9767 when others =>
9768 null;
9769 end case;
9770
9771 when N_Or_Else =>
9772 Traverse (Left_Opnd (N));
9773 return Skip;
9774
9775 when N_Selected_Component =>
9776 Set_Do_Discriminant_Check (N, False);
9777
9778 when N_Type_Conversion =>
9779 Set_Do_Length_Check (N, False);
9780 Set_Do_Tag_Check (N, False);
9781 Set_Do_Overflow_Check (N, False);
9782
9783 when others =>
9784 null;
9785 end case;
9786
9787 return OK;
9788 end Process;
9789
9790 -- Start of processing for Remove_Checks
9791
9792 begin
9793 Traverse (Expr);
9794 end Remove_Checks;
9795
9796 ----------------------------
9797 -- Selected_Length_Checks --
9798 ----------------------------
9799
9800 function Selected_Length_Checks
9801 (Expr : Node_Id;
9802 Target_Typ : Entity_Id;
9803 Source_Typ : Entity_Id;
9804 Warn_Node : Node_Id) return Check_Result
9805 is
9806 Loc : constant Source_Ptr := Sloc (Expr);
9807 S_Typ : Entity_Id;
9808 T_Typ : Entity_Id;
9809 Expr_Actual : Node_Id;
9810 Exptyp : Entity_Id;
9811 Cond : Node_Id := Empty;
9812 Do_Access : Boolean := False;
9813 Wnode : Node_Id := Warn_Node;
9814 Ret_Result : Check_Result := (Empty, Empty);
9815 Num_Checks : Natural := 0;
9816
9817 procedure Add_Check (N : Node_Id);
9818 -- Adds the action given to Ret_Result if N is non-Empty
9819
9820 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
9821 -- Return E'Length (Indx)
9822
9823 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
9824 -- Return N'Length (Indx)
9825
9826 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
9827 -- True for equal literals and for nodes that denote the same constant
9828 -- entity, even if its value is not a static constant. This includes the
9829 -- case of a discriminal reference within an init proc. Removes some
9830 -- obviously superfluous checks.
9831
9832 function Length_E_Cond
9833 (Exptyp : Entity_Id;
9834 Typ : Entity_Id;
9835 Indx : Nat) return Node_Id;
9836 -- Returns expression to compute:
9837 -- Typ'Length /= Exptyp'Length
9838
9839 function Length_N_Cond
9840 (Exp : Node_Id;
9841 Typ : Entity_Id;
9842 Indx : Nat) return Node_Id;
9843 -- Returns expression to compute:
9844 -- Typ'Length /= Exp'Length
9845
9846 function Length_Mismatch_Info_Message
9847 (Left_Element_Count : Uint;
9848 Right_Element_Count : Uint) return String;
9849 -- Returns a message indicating how many elements were expected
9850 -- (Left_Element_Count) and how many were found (Right_Element_Count).
9851
9852 ---------------
9853 -- Add_Check --
9854 ---------------
9855
9856 procedure Add_Check (N : Node_Id) is
9857 begin
9858 if Present (N) then
9859
9860 -- We do not support inserting more than 2 checks on the same
9861 -- node. If this happens it means we have already added an
9862 -- unconditional raise, so we can skip the other checks safely
9863 -- since N will always raise an exception.
9864
9865 if Num_Checks = 2 then
9866 return;
9867 end if;
9868
9869 pragma Assert (Num_Checks <= 1);
9870 Num_Checks := Num_Checks + 1;
9871 Ret_Result (Num_Checks) := N;
9872 end if;
9873 end Add_Check;
9874
9875 ------------------
9876 -- Get_E_Length --
9877 ------------------
9878
9879 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
9880 SE : constant Entity_Id := Scope (E);
9881 N : Node_Id;
9882 E1 : Entity_Id := E;
9883
9884 begin
9885 if Ekind (Scope (E)) = E_Record_Type
9886 and then Has_Discriminants (Scope (E))
9887 then
9888 N := Build_Discriminal_Subtype_Of_Component (E);
9889
9890 if Present (N) then
9891 Insert_Action (Expr, N);
9892 E1 := Defining_Identifier (N);
9893 end if;
9894 end if;
9895
9896 if Ekind (E1) = E_String_Literal_Subtype then
9897 return
9898 Make_Integer_Literal (Loc,
9899 Intval => String_Literal_Length (E1));
9900
9901 elsif SE /= Standard_Standard
9902 and then Ekind (Scope (SE)) = E_Protected_Type
9903 and then Has_Discriminants (Scope (SE))
9904 and then Has_Completion (Scope (SE))
9905 and then not Inside_Init_Proc
9906 then
9907 -- If the type whose length is needed is a private component
9908 -- constrained by a discriminant, we must expand the 'Length
9909 -- attribute into an explicit computation, using the discriminal
9910 -- of the current protected operation. This is because the actual
9911 -- type of the prival is constructed after the protected opera-
9912 -- tion has been fully expanded.
9913
9914 declare
9915 Indx_Type : Node_Id;
9916 Lo : Node_Id;
9917 Hi : Node_Id;
9918 Do_Expand : Boolean := False;
9919
9920 begin
9921 Indx_Type := First_Index (E);
9922
9923 for J in 1 .. Indx - 1 loop
9924 Next_Index (Indx_Type);
9925 end loop;
9926
9927 Get_Index_Bounds (Indx_Type, Lo, Hi);
9928
9929 if Nkind (Lo) = N_Identifier
9930 and then Ekind (Entity (Lo)) = E_In_Parameter
9931 then
9932 Lo := Get_Discriminal (E, Lo);
9933 Do_Expand := True;
9934 end if;
9935
9936 if Nkind (Hi) = N_Identifier
9937 and then Ekind (Entity (Hi)) = E_In_Parameter
9938 then
9939 Hi := Get_Discriminal (E, Hi);
9940 Do_Expand := True;
9941 end if;
9942
9943 if Do_Expand then
9944 if not Is_Entity_Name (Lo) then
9945 Lo := Duplicate_Subexpr_No_Checks (Lo);
9946 end if;
9947
9948 if not Is_Entity_Name (Hi) then
9949 Lo := Duplicate_Subexpr_No_Checks (Hi);
9950 end if;
9951
9952 N :=
9953 Make_Op_Add (Loc,
9954 Left_Opnd =>
9955 Make_Op_Subtract (Loc,
9956 Left_Opnd => Hi,
9957 Right_Opnd => Lo),
9958
9959 Right_Opnd => Make_Integer_Literal (Loc, 1));
9960 return N;
9961
9962 else
9963 N :=
9964 Make_Attribute_Reference (Loc,
9965 Attribute_Name => Name_Length,
9966 Prefix =>
9967 New_Occurrence_Of (E1, Loc));
9968
9969 if Indx > 1 then
9970 Set_Expressions (N, New_List (
9971 Make_Integer_Literal (Loc, Indx)));
9972 end if;
9973
9974 return N;
9975 end if;
9976 end;
9977
9978 else
9979 N :=
9980 Make_Attribute_Reference (Loc,
9981 Attribute_Name => Name_Length,
9982 Prefix =>
9983 New_Occurrence_Of (E1, Loc));
9984
9985 if Indx > 1 then
9986 Set_Expressions (N, New_List (
9987 Make_Integer_Literal (Loc, Indx)));
9988 end if;
9989
9990 return N;
9991 end if;
9992 end Get_E_Length;
9993
9994 ------------------
9995 -- Get_N_Length --
9996 ------------------
9997
9998 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
9999 begin
10000 return
10001 Make_Attribute_Reference (Loc,
10002 Attribute_Name => Name_Length,
10003 Prefix =>
10004 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10005 Expressions => New_List (
10006 Make_Integer_Literal (Loc, Indx)));
10007 end Get_N_Length;
10008
10009 -------------------
10010 -- Length_E_Cond --
10011 -------------------
10012
10013 function Length_E_Cond
10014 (Exptyp : Entity_Id;
10015 Typ : Entity_Id;
10016 Indx : Nat) return Node_Id
10017 is
10018 begin
10019 return
10020 Make_Op_Ne (Loc,
10021 Left_Opnd => Get_E_Length (Typ, Indx),
10022 Right_Opnd => Get_E_Length (Exptyp, Indx));
10023 end Length_E_Cond;
10024
10025 -------------------
10026 -- Length_N_Cond --
10027 -------------------
10028
10029 function Length_N_Cond
10030 (Exp : Node_Id;
10031 Typ : Entity_Id;
10032 Indx : Nat) return Node_Id
10033 is
10034 begin
10035 return
10036 Make_Op_Ne (Loc,
10037 Left_Opnd => Get_E_Length (Typ, Indx),
10038 Right_Opnd => Get_N_Length (Exp, Indx));
10039 end Length_N_Cond;
10040
10041 ----------------------------------
10042 -- Length_Mismatch_Info_Message --
10043 ----------------------------------
10044
10045 function Length_Mismatch_Info_Message
10046 (Left_Element_Count : Uint;
10047 Right_Element_Count : Uint) return String
10048 is
10049
10050 function Plural_Vs_Singular_Ending (Count : Uint) return String;
10051 -- Returns an empty string if Count is 1; otherwise returns "s"
10052
10053 function Plural_Vs_Singular_Ending (Count : Uint) return String is
10054 begin
10055 if Count = 1 then
10056 return "";
10057 else
10058 return "s";
10059 end if;
10060 end Plural_Vs_Singular_Ending;
10061
10062 begin
10063 return "expected " & UI_Image (Left_Element_Count)
10064 & " element"
10065 & Plural_Vs_Singular_Ending (Left_Element_Count)
10066 & "; found " & UI_Image (Right_Element_Count)
10067 & " element"
10068 & Plural_Vs_Singular_Ending (Right_Element_Count);
10069 end Length_Mismatch_Info_Message;
10070
10071 -----------------
10072 -- Same_Bounds --
10073 -----------------
10074
10075 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
10076 begin
10077 return
10078 (Nkind (L) = N_Integer_Literal
10079 and then Nkind (R) = N_Integer_Literal
10080 and then Intval (L) = Intval (R))
10081
10082 or else
10083 (Is_Entity_Name (L)
10084 and then Ekind (Entity (L)) = E_Constant
10085 and then ((Is_Entity_Name (R)
10086 and then Entity (L) = Entity (R))
10087 or else
10088 (Nkind (R) = N_Type_Conversion
10089 and then Is_Entity_Name (Expression (R))
10090 and then Entity (L) = Entity (Expression (R)))))
10091
10092 or else
10093 (Is_Entity_Name (R)
10094 and then Ekind (Entity (R)) = E_Constant
10095 and then Nkind (L) = N_Type_Conversion
10096 and then Is_Entity_Name (Expression (L))
10097 and then Entity (R) = Entity (Expression (L)))
10098
10099 or else
10100 (Is_Entity_Name (L)
10101 and then Is_Entity_Name (R)
10102 and then Entity (L) = Entity (R)
10103 and then Ekind (Entity (L)) = E_In_Parameter
10104 and then Inside_Init_Proc);
10105 end Same_Bounds;
10106
10107 -- Start of processing for Selected_Length_Checks
10108
10109 begin
10110 -- Checks will be applied only when generating code
10111
10112 if not Expander_Active then
10113 return Ret_Result;
10114 end if;
10115
10116 if Target_Typ = Any_Type
10117 or else Target_Typ = Any_Composite
10118 or else Raises_Constraint_Error (Expr)
10119 then
10120 return Ret_Result;
10121 end if;
10122
10123 if No (Wnode) then
10124 Wnode := Expr;
10125 end if;
10126
10127 T_Typ := Target_Typ;
10128
10129 if No (Source_Typ) then
10130 S_Typ := Etype (Expr);
10131 else
10132 S_Typ := Source_Typ;
10133 end if;
10134
10135 if S_Typ = Any_Type or else S_Typ = Any_Composite then
10136 return Ret_Result;
10137 end if;
10138
10139 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
10140 S_Typ := Designated_Type (S_Typ);
10141 T_Typ := Designated_Type (T_Typ);
10142 Do_Access := True;
10143
10144 -- A simple optimization for the null case
10145
10146 if Known_Null (Expr) then
10147 return Ret_Result;
10148 end if;
10149 end if;
10150
10151 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
10152 if Is_Constrained (T_Typ) then
10153
10154 -- The checking code to be generated will freeze the corresponding
10155 -- array type. However, we must freeze the type now, so that the
10156 -- freeze node does not appear within the generated if expression,
10157 -- but ahead of it.
10158
10159 Freeze_Before (Expr, T_Typ);
10160
10161 Expr_Actual := Get_Referenced_Object (Expr);
10162 Exptyp := Get_Actual_Subtype (Expr);
10163
10164 if Is_Access_Type (Exptyp) then
10165 Exptyp := Designated_Type (Exptyp);
10166 end if;
10167
10168 -- String_Literal case. This needs to be handled specially be-
10169 -- cause no index types are available for string literals. The
10170 -- condition is simply:
10171
10172 -- T_Typ'Length = string-literal-length
10173
10174 if Nkind (Expr_Actual) = N_String_Literal
10175 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
10176 then
10177 Cond :=
10178 Make_Op_Ne (Loc,
10179 Left_Opnd => Get_E_Length (T_Typ, 1),
10180 Right_Opnd =>
10181 Make_Integer_Literal (Loc,
10182 Intval =>
10183 String_Literal_Length (Etype (Expr_Actual))));
10184
10185 -- General array case. Here we have a usable actual subtype for
10186 -- the expression, and the condition is built from the two types
10187 -- (Do_Length):
10188
10189 -- T_Typ'Length /= Exptyp'Length or else
10190 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
10191 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
10192 -- ...
10193
10194 elsif Is_Constrained (Exptyp) then
10195 declare
10196 Ndims : constant Nat := Number_Dimensions (T_Typ);
10197
10198 L_Index : Node_Id;
10199 R_Index : Node_Id;
10200 L_Low : Node_Id;
10201 L_High : Node_Id;
10202 R_Low : Node_Id;
10203 R_High : Node_Id;
10204 L_Length : Uint;
10205 R_Length : Uint;
10206 Ref_Node : Node_Id;
10207
10208 begin
10209 -- At the library level, we need to ensure that the type of
10210 -- the object is elaborated before the check itself is
10211 -- emitted. This is only done if the object is in the
10212 -- current compilation unit, otherwise the type is frozen
10213 -- and elaborated in its unit.
10214
10215 if Is_Itype (Exptyp)
10216 and then
10217 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
10218 and then
10219 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
10220 and then In_Open_Scopes (Scope (Exptyp))
10221 then
10222 Ref_Node := Make_Itype_Reference (Sloc (Expr));
10223 Set_Itype (Ref_Node, Exptyp);
10224 Insert_Action (Expr, Ref_Node);
10225 end if;
10226
10227 L_Index := First_Index (T_Typ);
10228 R_Index := First_Index (Exptyp);
10229
10230 for Indx in 1 .. Ndims loop
10231 if not (Nkind (L_Index) = N_Raise_Constraint_Error
10232 or else
10233 Nkind (R_Index) = N_Raise_Constraint_Error)
10234 then
10235 Get_Index_Bounds (L_Index, L_Low, L_High);
10236 Get_Index_Bounds (R_Index, R_Low, R_High);
10237
10238 -- Deal with compile time length check. Note that we
10239 -- skip this in the access case, because the access
10240 -- value may be null, so we cannot know statically.
10241
10242 if not Do_Access
10243 and then Compile_Time_Known_Value (L_Low)
10244 and then Compile_Time_Known_Value (L_High)
10245 and then Compile_Time_Known_Value (R_Low)
10246 and then Compile_Time_Known_Value (R_High)
10247 then
10248 if Expr_Value (L_High) >= Expr_Value (L_Low) then
10249 L_Length := Expr_Value (L_High) -
10250 Expr_Value (L_Low) + 1;
10251 else
10252 L_Length := UI_From_Int (0);
10253 end if;
10254
10255 if Expr_Value (R_High) >= Expr_Value (R_Low) then
10256 R_Length := Expr_Value (R_High) -
10257 Expr_Value (R_Low) + 1;
10258 else
10259 R_Length := UI_From_Int (0);
10260 end if;
10261
10262 if L_Length > R_Length then
10263 Add_Check
10264 (Compile_Time_Constraint_Error
10265 (Wnode, "too few elements for}??", T_Typ,
10266 Extra_Msg => Length_Mismatch_Info_Message
10267 (L_Length, R_Length)));
10268
10269 elsif L_Length < R_Length then
10270 Add_Check
10271 (Compile_Time_Constraint_Error
10272 (Wnode, "too many elements for}??", T_Typ,
10273 Extra_Msg => Length_Mismatch_Info_Message
10274 (L_Length, R_Length)));
10275 end if;
10276
10277 -- The comparison for an individual index subtype
10278 -- is omitted if the corresponding index subtypes
10279 -- statically match, since the result is known to
10280 -- be true. Note that this test is worth while even
10281 -- though we do static evaluation, because non-static
10282 -- subtypes can statically match.
10283
10284 elsif not
10285 Subtypes_Statically_Match
10286 (Etype (L_Index), Etype (R_Index))
10287
10288 and then not
10289 (Same_Bounds (L_Low, R_Low)
10290 and then Same_Bounds (L_High, R_High))
10291 then
10292 Evolve_Or_Else
10293 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
10294 end if;
10295
10296 Next (L_Index);
10297 Next (R_Index);
10298 end if;
10299 end loop;
10300 end;
10301
10302 -- Handle cases where we do not get a usable actual subtype that
10303 -- is constrained. This happens for example in the function call
10304 -- and explicit dereference cases. In these cases, we have to get
10305 -- the length or range from the expression itself, making sure we
10306 -- do not evaluate it more than once.
10307
10308 -- Here Expr is the original expression, or more properly the
10309 -- result of applying Duplicate_Expr to the original tree, forcing
10310 -- the result to be a name.
10311
10312 else
10313 declare
10314 Ndims : constant Pos := Number_Dimensions (T_Typ);
10315
10316 begin
10317 -- Build the condition for the explicit dereference case
10318
10319 for Indx in 1 .. Ndims loop
10320 Evolve_Or_Else
10321 (Cond, Length_N_Cond (Expr, T_Typ, Indx));
10322 end loop;
10323 end;
10324 end if;
10325 end if;
10326 end if;
10327
10328 -- Construct the test and insert into the tree
10329
10330 if Present (Cond) then
10331 if Do_Access then
10332 Cond := Guard_Access (Cond, Loc, Expr);
10333 end if;
10334
10335 Add_Check
10336 (Make_Raise_Constraint_Error (Loc,
10337 Condition => Cond,
10338 Reason => CE_Length_Check_Failed));
10339 end if;
10340
10341 return Ret_Result;
10342 end Selected_Length_Checks;
10343
10344 ---------------------------
10345 -- Selected_Range_Checks --
10346 ---------------------------
10347
10348 function Selected_Range_Checks
10349 (Expr : Node_Id;
10350 Target_Typ : Entity_Id;
10351 Source_Typ : Entity_Id;
10352 Warn_Node : Node_Id) return Check_Result
10353 is
10354 Loc : constant Source_Ptr := Sloc (Expr);
10355 S_Typ : Entity_Id;
10356 T_Typ : Entity_Id;
10357 Expr_Actual : Node_Id;
10358 Exptyp : Entity_Id;
10359 Cond : Node_Id := Empty;
10360 Do_Access : Boolean := False;
10361 Wnode : Node_Id := Warn_Node;
10362 Ret_Result : Check_Result := (Empty, Empty);
10363 Num_Checks : Natural := 0;
10364
10365 procedure Add_Check (N : Node_Id);
10366 -- Adds the action given to Ret_Result if N is non-Empty
10367
10368 function Discrete_Range_Cond
10369 (Exp : Node_Id;
10370 Typ : Entity_Id) return Node_Id;
10371 -- Returns expression to compute:
10372 -- Low_Bound (Exp) < Typ'First
10373 -- or else
10374 -- High_Bound (Exp) > Typ'Last
10375
10376 function Discrete_Expr_Cond
10377 (Exp : Node_Id;
10378 Typ : Entity_Id) return Node_Id;
10379 -- Returns expression to compute:
10380 -- Exp < Typ'First
10381 -- or else
10382 -- Exp > Typ'Last
10383
10384 function Get_E_First_Or_Last
10385 (Loc : Source_Ptr;
10386 E : Entity_Id;
10387 Indx : Nat;
10388 Nam : Name_Id) return Node_Id;
10389 -- Returns an attribute reference
10390 -- E'First or E'Last
10391 -- with a source location of Loc.
10392 --
10393 -- Nam is Name_First or Name_Last, according to which attribute is
10394 -- desired. If Indx is non-zero, it is passed as a literal in the
10395 -- Expressions of the attribute reference (identifying the desired
10396 -- array dimension).
10397
10398 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
10399 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
10400 -- Returns expression to compute:
10401 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
10402
10403 function Range_E_Cond
10404 (Exptyp : Entity_Id;
10405 Typ : Entity_Id;
10406 Indx : Nat)
10407 return Node_Id;
10408 -- Returns expression to compute:
10409 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
10410
10411 function Range_Equal_E_Cond
10412 (Exptyp : Entity_Id;
10413 Typ : Entity_Id;
10414 Indx : Nat) return Node_Id;
10415 -- Returns expression to compute:
10416 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
10417
10418 function Range_N_Cond
10419 (Exp : Node_Id;
10420 Typ : Entity_Id;
10421 Indx : Nat) return Node_Id;
10422 -- Return expression to compute:
10423 -- Exp'First < Typ'First or else Exp'Last > Typ'Last
10424
10425 ---------------
10426 -- Add_Check --
10427 ---------------
10428
10429 procedure Add_Check (N : Node_Id) is
10430 begin
10431 if Present (N) then
10432
10433 -- We do not support inserting more than 2 checks on the same
10434 -- node. If this happens it means we have already added an
10435 -- unconditional raise, so we can skip the other checks safely
10436 -- since N will always raise an exception.
10437
10438 if Num_Checks = 2 then
10439 return;
10440 end if;
10441
10442 pragma Assert (Num_Checks <= 1);
10443 Num_Checks := Num_Checks + 1;
10444 Ret_Result (Num_Checks) := N;
10445 end if;
10446 end Add_Check;
10447
10448 -------------------------
10449 -- Discrete_Expr_Cond --
10450 -------------------------
10451
10452 function Discrete_Expr_Cond
10453 (Exp : Node_Id;
10454 Typ : Entity_Id) return Node_Id
10455 is
10456 begin
10457 return
10458 Make_Or_Else (Loc,
10459 Left_Opnd =>
10460 Make_Op_Lt (Loc,
10461 Left_Opnd =>
10462 Convert_To (Base_Type (Typ),
10463 Duplicate_Subexpr_No_Checks (Exp)),
10464 Right_Opnd =>
10465 Convert_To (Base_Type (Typ),
10466 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
10467
10468 Right_Opnd =>
10469 Make_Op_Gt (Loc,
10470 Left_Opnd =>
10471 Convert_To (Base_Type (Typ),
10472 Duplicate_Subexpr_No_Checks (Exp)),
10473 Right_Opnd =>
10474 Convert_To
10475 (Base_Type (Typ),
10476 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
10477 end Discrete_Expr_Cond;
10478
10479 -------------------------
10480 -- Discrete_Range_Cond --
10481 -------------------------
10482
10483 function Discrete_Range_Cond
10484 (Exp : Node_Id;
10485 Typ : Entity_Id) return Node_Id
10486 is
10487 LB : Node_Id := Low_Bound (Exp);
10488 HB : Node_Id := High_Bound (Exp);
10489
10490 Left_Opnd : Node_Id;
10491 Right_Opnd : Node_Id;
10492
10493 begin
10494 if Nkind (LB) = N_Identifier
10495 and then Ekind (Entity (LB)) = E_Discriminant
10496 then
10497 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10498 end if;
10499
10500 Left_Opnd :=
10501 Make_Op_Lt (Loc,
10502 Left_Opnd =>
10503 Convert_To
10504 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
10505
10506 Right_Opnd =>
10507 Convert_To
10508 (Base_Type (Typ),
10509 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
10510
10511 if Nkind (HB) = N_Identifier
10512 and then Ekind (Entity (HB)) = E_Discriminant
10513 then
10514 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10515 end if;
10516
10517 Right_Opnd :=
10518 Make_Op_Gt (Loc,
10519 Left_Opnd =>
10520 Convert_To
10521 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
10522
10523 Right_Opnd =>
10524 Convert_To
10525 (Base_Type (Typ),
10526 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
10527
10528 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
10529 end Discrete_Range_Cond;
10530
10531 -------------------------
10532 -- Get_E_First_Or_Last --
10533 -------------------------
10534
10535 function Get_E_First_Or_Last
10536 (Loc : Source_Ptr;
10537 E : Entity_Id;
10538 Indx : Nat;
10539 Nam : Name_Id) return Node_Id
10540 is
10541 Exprs : List_Id;
10542 begin
10543 if Indx > 0 then
10544 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
10545 else
10546 Exprs := No_List;
10547 end if;
10548
10549 return Make_Attribute_Reference (Loc,
10550 Prefix => New_Occurrence_Of (E, Loc),
10551 Attribute_Name => Nam,
10552 Expressions => Exprs);
10553 end Get_E_First_Or_Last;
10554
10555 -----------------
10556 -- Get_N_First --
10557 -----------------
10558
10559 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
10560 begin
10561 return
10562 Make_Attribute_Reference (Loc,
10563 Attribute_Name => Name_First,
10564 Prefix =>
10565 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10566 Expressions => New_List (
10567 Make_Integer_Literal (Loc, Indx)));
10568 end Get_N_First;
10569
10570 ----------------
10571 -- Get_N_Last --
10572 ----------------
10573
10574 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
10575 begin
10576 return
10577 Make_Attribute_Reference (Loc,
10578 Attribute_Name => Name_Last,
10579 Prefix =>
10580 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10581 Expressions => New_List (
10582 Make_Integer_Literal (Loc, Indx)));
10583 end Get_N_Last;
10584
10585 ------------------
10586 -- Range_E_Cond --
10587 ------------------
10588
10589 function Range_E_Cond
10590 (Exptyp : Entity_Id;
10591 Typ : Entity_Id;
10592 Indx : Nat) return Node_Id
10593 is
10594 begin
10595 return
10596 Make_Or_Else (Loc,
10597 Left_Opnd =>
10598 Make_Op_Lt (Loc,
10599 Left_Opnd =>
10600 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10601 Right_Opnd =>
10602 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10603
10604 Right_Opnd =>
10605 Make_Op_Gt (Loc,
10606 Left_Opnd =>
10607 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10608 Right_Opnd =>
10609 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10610 end Range_E_Cond;
10611
10612 ------------------------
10613 -- Range_Equal_E_Cond --
10614 ------------------------
10615
10616 function Range_Equal_E_Cond
10617 (Exptyp : Entity_Id;
10618 Typ : Entity_Id;
10619 Indx : Nat) return Node_Id
10620 is
10621 begin
10622 return
10623 Make_Or_Else (Loc,
10624 Left_Opnd =>
10625 Make_Op_Ne (Loc,
10626 Left_Opnd =>
10627 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10628 Right_Opnd =>
10629 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10630
10631 Right_Opnd =>
10632 Make_Op_Ne (Loc,
10633 Left_Opnd =>
10634 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10635 Right_Opnd =>
10636 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10637 end Range_Equal_E_Cond;
10638
10639 ------------------
10640 -- Range_N_Cond --
10641 ------------------
10642
10643 function Range_N_Cond
10644 (Exp : Node_Id;
10645 Typ : Entity_Id;
10646 Indx : Nat) return Node_Id
10647 is
10648 begin
10649 return
10650 Make_Or_Else (Loc,
10651 Left_Opnd =>
10652 Make_Op_Lt (Loc,
10653 Left_Opnd =>
10654 Get_N_First (Exp, Indx),
10655 Right_Opnd =>
10656 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10657
10658 Right_Opnd =>
10659 Make_Op_Gt (Loc,
10660 Left_Opnd =>
10661 Get_N_Last (Exp, Indx),
10662 Right_Opnd =>
10663 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10664 end Range_N_Cond;
10665
10666 function "<" (Left, Right : Node_Id) return Boolean
10667 is (if Is_Floating_Point_Type (S_Typ)
10668 then Expr_Value_R (Left) < Expr_Value_R (Right)
10669 else Expr_Value (Left) < Expr_Value (Right));
10670 -- Convenience comparison function of integer or floating point
10671 -- values.
10672
10673 -- Start of processing for Selected_Range_Checks
10674
10675 begin
10676 -- Checks will be applied only when generating code. In GNATprove mode,
10677 -- we do not apply the checks, but we still call Selected_Range_Checks
10678 -- outside of generics to possibly issue errors on SPARK code when a
10679 -- run-time error can be detected at compile time.
10680
10681 if Inside_A_Generic or (not GNATprove_Mode and not Expander_Active) then
10682 return Ret_Result;
10683 end if;
10684
10685 if Target_Typ = Any_Type
10686 or else Target_Typ = Any_Composite
10687 or else Raises_Constraint_Error (Expr)
10688 then
10689 return Ret_Result;
10690 end if;
10691
10692 if No (Wnode) then
10693 Wnode := Expr;
10694 end if;
10695
10696 T_Typ := Target_Typ;
10697
10698 if No (Source_Typ) then
10699 S_Typ := Etype (Expr);
10700 else
10701 S_Typ := Source_Typ;
10702 end if;
10703
10704 if S_Typ = Any_Type or else S_Typ = Any_Composite then
10705 return Ret_Result;
10706 end if;
10707
10708 -- The order of evaluating T_Typ before S_Typ seems to be critical
10709 -- because S_Typ can be derived from Etype (Expr), if it's not passed
10710 -- in, and since Node can be an N_Range node, it might be invalid.
10711 -- Should there be an assert check somewhere for taking the Etype of
10712 -- an N_Range node ???
10713
10714 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
10715 S_Typ := Designated_Type (S_Typ);
10716 T_Typ := Designated_Type (T_Typ);
10717 Do_Access := True;
10718
10719 -- A simple optimization for the null case
10720
10721 if Known_Null (Expr) then
10722 return Ret_Result;
10723 end if;
10724 end if;
10725
10726 -- For an N_Range Node, check for a null range and then if not
10727 -- null generate a range check action.
10728
10729 if Nkind (Expr) = N_Range then
10730
10731 -- There's no point in checking a range against itself
10732
10733 if Expr = Scalar_Range (T_Typ) then
10734 return Ret_Result;
10735 end if;
10736
10737 declare
10738 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
10739 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
10740 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
10741 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
10742
10743 LB : Node_Id := Low_Bound (Expr);
10744 HB : Node_Id := High_Bound (Expr);
10745 Known_LB : Boolean := False;
10746 Known_HB : Boolean := False;
10747 Check_Added : Boolean := False;
10748
10749 Out_Of_Range_L : Boolean := False;
10750 Out_Of_Range_H : Boolean := False;
10751
10752 begin
10753 -- Compute what is known at compile time
10754
10755 if Known_T_LB and Known_T_HB then
10756 if Compile_Time_Known_Value (LB) then
10757 Known_LB := True;
10758
10759 -- There's no point in checking that a bound is within its
10760 -- own range so pretend that it is known in this case. First
10761 -- deal with low bound.
10762
10763 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
10764 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
10765 then
10766 LB := T_LB;
10767 Known_LB := True;
10768 end if;
10769
10770 -- Likewise for the high bound
10771
10772 if Compile_Time_Known_Value (HB) then
10773 Known_HB := True;
10774
10775 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
10776 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
10777 then
10778 HB := T_HB;
10779 Known_HB := True;
10780 end if;
10781 end if;
10782
10783 -- Check for the simple cases where we can do the check at
10784 -- compile time. This is skipped if we have an access type, since
10785 -- the access value may be null.
10786
10787 if not Do_Access and then Not_Null_Range (LB, HB) then
10788 if Known_LB then
10789 if Known_T_LB then
10790 Out_Of_Range_L := LB < T_LB;
10791 end if;
10792
10793 if Known_T_HB and not Out_Of_Range_L then
10794 Out_Of_Range_L := T_HB < LB;
10795 end if;
10796
10797 if Out_Of_Range_L then
10798 if No (Warn_Node) then
10799 Add_Check
10800 (Compile_Time_Constraint_Error
10801 (Low_Bound (Expr),
10802 "static value out of range of}??", T_Typ));
10803 Check_Added := True;
10804
10805 else
10806 Add_Check
10807 (Compile_Time_Constraint_Error
10808 (Wnode,
10809 "static range out of bounds of}??", T_Typ));
10810 Check_Added := True;
10811 end if;
10812 end if;
10813 end if;
10814
10815 if Known_HB then
10816 if Known_T_HB then
10817 Out_Of_Range_H := T_HB < HB;
10818 end if;
10819
10820 if Known_T_LB and not Out_Of_Range_H then
10821 Out_Of_Range_H := HB < T_LB;
10822 end if;
10823
10824 if Out_Of_Range_H then
10825 if No (Warn_Node) then
10826 Add_Check
10827 (Compile_Time_Constraint_Error
10828 (High_Bound (Expr),
10829 "static value out of range of}??", T_Typ));
10830 Check_Added := True;
10831
10832 else
10833 Add_Check
10834 (Compile_Time_Constraint_Error
10835 (Wnode,
10836 "static range out of bounds of}??", T_Typ));
10837 Check_Added := True;
10838 end if;
10839 end if;
10840 end if;
10841 end if;
10842
10843 -- Check for the case where not everything is static
10844
10845 if not Check_Added
10846 and then
10847 (Do_Access
10848 or else not Known_T_LB
10849 or else not Known_LB
10850 or else not Known_T_HB
10851 or else not Known_HB)
10852 then
10853 declare
10854 LB : Node_Id := Low_Bound (Expr);
10855 HB : Node_Id := High_Bound (Expr);
10856
10857 begin
10858 -- If either bound is a discriminant and we are within the
10859 -- record declaration, it is a use of the discriminant in a
10860 -- constraint of a component, and nothing can be checked
10861 -- here. The check will be emitted within the init proc.
10862 -- Before then, the discriminal has no real meaning.
10863 -- Similarly, if the entity is a discriminal, there is no
10864 -- check to perform yet.
10865
10866 -- The same holds within a discriminated synchronized type,
10867 -- where the discriminant may constrain a component or an
10868 -- entry family.
10869
10870 if Nkind (LB) = N_Identifier
10871 and then Denotes_Discriminant (LB, True)
10872 then
10873 if Current_Scope = Scope (Entity (LB))
10874 or else Is_Concurrent_Type (Current_Scope)
10875 or else Ekind (Entity (LB)) /= E_Discriminant
10876 then
10877 return Ret_Result;
10878 else
10879 LB :=
10880 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10881 end if;
10882 end if;
10883
10884 if Nkind (HB) = N_Identifier
10885 and then Denotes_Discriminant (HB, True)
10886 then
10887 if Current_Scope = Scope (Entity (HB))
10888 or else Is_Concurrent_Type (Current_Scope)
10889 or else Ekind (Entity (HB)) /= E_Discriminant
10890 then
10891 return Ret_Result;
10892 else
10893 HB :=
10894 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10895 end if;
10896 end if;
10897
10898 Cond := Discrete_Range_Cond (Expr, T_Typ);
10899 Set_Paren_Count (Cond, 1);
10900
10901 Cond :=
10902 Make_And_Then (Loc,
10903 Left_Opnd =>
10904 Make_Op_Ge (Loc,
10905 Left_Opnd =>
10906 Convert_To (Base_Type (Etype (HB)),
10907 Duplicate_Subexpr_No_Checks (HB)),
10908 Right_Opnd =>
10909 Convert_To (Base_Type (Etype (LB)),
10910 Duplicate_Subexpr_No_Checks (LB))),
10911 Right_Opnd => Cond);
10912 end;
10913 end if;
10914 end;
10915
10916 elsif Is_Scalar_Type (S_Typ) then
10917
10918 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10919 -- except the above simply sets a flag in the node and lets the
10920 -- check be generated based on the Etype of the expression.
10921 -- Sometimes, however we want to do a dynamic check against an
10922 -- arbitrary target type, so we do that here.
10923
10924 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
10925 Cond := Discrete_Expr_Cond (Expr, T_Typ);
10926
10927 -- For literals, we can tell if the constraint error will be
10928 -- raised at compile time, so we never need a dynamic check, but
10929 -- if the exception will be raised, then post the usual warning,
10930 -- and replace the literal with a raise constraint error
10931 -- expression. As usual, skip this for access types
10932
10933 elsif Compile_Time_Known_Value (Expr) and then not Do_Access then
10934 if Is_Out_Of_Range (Expr, T_Typ) then
10935
10936 -- Bounds of the type are static and the literal is out of
10937 -- range so output a warning message.
10938
10939 if No (Warn_Node) then
10940 Add_Check
10941 (Compile_Time_Constraint_Error
10942 (Expr, "static value out of range of}??", T_Typ));
10943
10944 else
10945 Add_Check
10946 (Compile_Time_Constraint_Error
10947 (Wnode, "static value out of range of}??", T_Typ));
10948 end if;
10949 else
10950 Cond := Discrete_Expr_Cond (Expr, T_Typ);
10951 end if;
10952
10953 -- Here for the case of a non-static expression, we need a runtime
10954 -- check unless the source type range is guaranteed to be in the
10955 -- range of the target type.
10956
10957 else
10958 if not In_Subrange_Of (S_Typ, T_Typ) then
10959 Cond := Discrete_Expr_Cond (Expr, T_Typ);
10960 end if;
10961 end if;
10962 end if;
10963
10964 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
10965 if Is_Constrained (T_Typ) then
10966
10967 Expr_Actual := Get_Referenced_Object (Expr);
10968 Exptyp := Get_Actual_Subtype (Expr_Actual);
10969
10970 if Is_Access_Type (Exptyp) then
10971 Exptyp := Designated_Type (Exptyp);
10972 end if;
10973
10974 -- String_Literal case. This needs to be handled specially be-
10975 -- cause no index types are available for string literals. The
10976 -- condition is simply:
10977
10978 -- T_Typ'Length = string-literal-length
10979
10980 if Nkind (Expr_Actual) = N_String_Literal then
10981 null;
10982
10983 -- General array case. Here we have a usable actual subtype for
10984 -- the expression, and the condition is built from the two types
10985
10986 -- T_Typ'First < Exptyp'First or else
10987 -- T_Typ'Last > Exptyp'Last or else
10988 -- T_Typ'First(1) < Exptyp'First(1) or else
10989 -- T_Typ'Last(1) > Exptyp'Last(1) or else
10990 -- ...
10991
10992 elsif Is_Constrained (Exptyp) then
10993 declare
10994 Ndims : constant Pos := Number_Dimensions (T_Typ);
10995
10996 L_Index : Node_Id;
10997 R_Index : Node_Id;
10998
10999 begin
11000 L_Index := First_Index (T_Typ);
11001 R_Index := First_Index (Exptyp);
11002
11003 for Indx in 1 .. Ndims loop
11004 if not (Nkind (L_Index) = N_Raise_Constraint_Error
11005 or else
11006 Nkind (R_Index) = N_Raise_Constraint_Error)
11007 then
11008 -- Deal with compile time length check. Note that we
11009 -- skip this in the access case, because the access
11010 -- value may be null, so we cannot know statically.
11011
11012 if not
11013 Subtypes_Statically_Match
11014 (Etype (L_Index), Etype (R_Index))
11015 then
11016 -- If the target type is constrained then we
11017 -- have to check for exact equality of bounds
11018 -- (required for qualified expressions).
11019
11020 if Is_Constrained (T_Typ) then
11021 Evolve_Or_Else
11022 (Cond,
11023 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
11024 else
11025 Evolve_Or_Else
11026 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
11027 end if;
11028 end if;
11029
11030 Next (L_Index);
11031 Next (R_Index);
11032 end if;
11033 end loop;
11034 end;
11035
11036 -- Handle cases where we do not get a usable actual subtype that
11037 -- is constrained. This happens for example in the function call
11038 -- and explicit dereference cases. In these cases, we have to get
11039 -- the length or range from the expression itself, making sure we
11040 -- do not evaluate it more than once.
11041
11042 -- Here Expr is the original expression, or more properly the
11043 -- result of applying Duplicate_Expr to the original tree,
11044 -- forcing the result to be a name.
11045
11046 else
11047 declare
11048 Ndims : constant Pos := Number_Dimensions (T_Typ);
11049
11050 begin
11051 -- Build the condition for the explicit dereference case
11052
11053 for Indx in 1 .. Ndims loop
11054 Evolve_Or_Else
11055 (Cond, Range_N_Cond (Expr, T_Typ, Indx));
11056 end loop;
11057 end;
11058 end if;
11059
11060 else
11061 -- For a conversion to an unconstrained array type, generate an
11062 -- Action to check that the bounds of the source value are within
11063 -- the constraints imposed by the target type (RM 4.6(38)). No
11064 -- check is needed for a conversion to an access to unconstrained
11065 -- array type, as 4.6(24.15/2) requires the designated subtypes
11066 -- of the two access types to statically match.
11067
11068 if Nkind (Parent (Expr)) = N_Type_Conversion
11069 and then not Do_Access
11070 then
11071 declare
11072 Opnd_Index : Node_Id;
11073 Targ_Index : Node_Id;
11074 Opnd_Range : Node_Id;
11075
11076 begin
11077 Opnd_Index := First_Index (Get_Actual_Subtype (Expr));
11078 Targ_Index := First_Index (T_Typ);
11079 while Present (Opnd_Index) loop
11080
11081 -- If the index is a range, use its bounds. If it is an
11082 -- entity (as will be the case if it is a named subtype
11083 -- or an itype created for a slice) retrieve its range.
11084
11085 if Is_Entity_Name (Opnd_Index)
11086 and then Is_Type (Entity (Opnd_Index))
11087 then
11088 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
11089 else
11090 Opnd_Range := Opnd_Index;
11091 end if;
11092
11093 if Nkind (Opnd_Range) = N_Range then
11094 if Is_In_Range
11095 (Low_Bound (Opnd_Range), Etype (Targ_Index),
11096 Assume_Valid => True)
11097 and then
11098 Is_In_Range
11099 (High_Bound (Opnd_Range), Etype (Targ_Index),
11100 Assume_Valid => True)
11101 then
11102 null;
11103
11104 -- If null range, no check needed
11105
11106 elsif
11107 Compile_Time_Known_Value (High_Bound (Opnd_Range))
11108 and then
11109 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
11110 and then
11111 Expr_Value (High_Bound (Opnd_Range)) <
11112 Expr_Value (Low_Bound (Opnd_Range))
11113 then
11114 null;
11115
11116 elsif Is_Out_Of_Range
11117 (Low_Bound (Opnd_Range), Etype (Targ_Index),
11118 Assume_Valid => True)
11119 or else
11120 Is_Out_Of_Range
11121 (High_Bound (Opnd_Range), Etype (Targ_Index),
11122 Assume_Valid => True)
11123 then
11124 Add_Check
11125 (Compile_Time_Constraint_Error
11126 (Wnode, "value out of range of}??", T_Typ));
11127
11128 else
11129 Evolve_Or_Else
11130 (Cond,
11131 Discrete_Range_Cond
11132 (Opnd_Range, Etype (Targ_Index)));
11133 end if;
11134 end if;
11135
11136 Next_Index (Opnd_Index);
11137 Next_Index (Targ_Index);
11138 end loop;
11139 end;
11140 end if;
11141 end if;
11142 end if;
11143
11144 -- Construct the test and insert into the tree
11145
11146 if Present (Cond) then
11147 if Do_Access then
11148 Cond := Guard_Access (Cond, Loc, Expr);
11149 end if;
11150
11151 Add_Check
11152 (Make_Raise_Constraint_Error (Loc,
11153 Condition => Cond,
11154 Reason => CE_Range_Check_Failed));
11155 end if;
11156
11157 return Ret_Result;
11158 end Selected_Range_Checks;
11159
11160 -------------------------------
11161 -- Storage_Checks_Suppressed --
11162 -------------------------------
11163
11164 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
11165 begin
11166 if Present (E) and then Checks_May_Be_Suppressed (E) then
11167 return Is_Check_Suppressed (E, Storage_Check);
11168 else
11169 return Scope_Suppress.Suppress (Storage_Check);
11170 end if;
11171 end Storage_Checks_Suppressed;
11172
11173 ---------------------------
11174 -- Tag_Checks_Suppressed --
11175 ---------------------------
11176
11177 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
11178 begin
11179 if Present (E)
11180 and then Checks_May_Be_Suppressed (E)
11181 then
11182 return Is_Check_Suppressed (E, Tag_Check);
11183 else
11184 return Scope_Suppress.Suppress (Tag_Check);
11185 end if;
11186 end Tag_Checks_Suppressed;
11187
11188 ---------------------------------------
11189 -- Validate_Alignment_Check_Warnings --
11190 ---------------------------------------
11191
11192 procedure Validate_Alignment_Check_Warnings is
11193 begin
11194 for J in Alignment_Warnings.First .. Alignment_Warnings.Last loop
11195 declare
11196 AWR : Alignment_Warnings_Record
11197 renames Alignment_Warnings.Table (J);
11198 begin
11199 if Known_Alignment (AWR.E)
11200 and then ((AWR.A /= No_Uint
11201 and then AWR.A mod Alignment (AWR.E) = 0)
11202 or else (Present (AWR.P)
11203 and then Has_Compatible_Alignment
11204 (AWR.E, AWR.P, True) =
11205 Known_Compatible))
11206 then
11207 Delete_Warning_And_Continuations (AWR.W);
11208 end if;
11209 end;
11210 end loop;
11211 end Validate_Alignment_Check_Warnings;
11212
11213 --------------------------
11214 -- Validity_Check_Range --
11215 --------------------------
11216
11217 procedure Validity_Check_Range
11218 (N : Node_Id;
11219 Related_Id : Entity_Id := Empty) is
11220 begin
11221 if Validity_Checks_On and Validity_Check_Operands then
11222 if Nkind (N) = N_Range then
11223 Ensure_Valid
11224 (Expr => Low_Bound (N),
11225 Related_Id => Related_Id,
11226 Is_Low_Bound => True);
11227
11228 Ensure_Valid
11229 (Expr => High_Bound (N),
11230 Related_Id => Related_Id,
11231 Is_High_Bound => True);
11232 end if;
11233 end if;
11234 end Validity_Check_Range;
11235
11236 end Checks;