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