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