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