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