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