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