PR rtl-optimization/79386
[official-gcc.git] / gcc / ada / checks.ads
blobff513e667b45106fdfb9f7380415caa79b4651f4
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- C H E C K S --
6 -- --
7 -- S p e c --
8 -- --
9 -- Copyright (C) 1992-2016, 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 ------------------------------------------------------------------------------
26 -- Package containing routines used to deal with runtime checks. These
27 -- routines are used both by the semantics and by the expander. In some
28 -- cases, checks are enabled simply by setting flags for gigi, and in
29 -- other cases the code for the check is expanded.
31 -- The approach used for range and length checks, in regards to suppressed
32 -- checks, is to attempt to detect at compilation time that a constraint
33 -- error will occur. If this is detected a warning or error is issued and the
34 -- offending expression or statement replaced with a constraint error node.
35 -- This always occurs whether checks are suppressed or not. Dynamic range
36 -- checks are, of course, not inserted if checks are suppressed.
38 with Errout; use Errout;
39 with Namet; use Namet;
40 with Table;
41 with Types; use Types;
42 with Uintp; use Uintp;
43 with Urealp; use Urealp;
45 package Checks is
47 procedure Initialize;
48 -- Called for each new main source program, to initialize internal
49 -- variables used in the package body of the Checks unit.
51 function Access_Checks_Suppressed (E : Entity_Id) return Boolean;
52 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean;
53 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean;
54 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean;
55 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean;
56 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean;
57 function Division_Checks_Suppressed (E : Entity_Id) return Boolean;
58 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean;
59 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean;
60 function Index_Checks_Suppressed (E : Entity_Id) return Boolean;
61 function Length_Checks_Suppressed (E : Entity_Id) return Boolean;
62 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean;
63 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean;
64 function Range_Checks_Suppressed (E : Entity_Id) return Boolean;
65 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean;
66 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean;
67 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean;
68 -- These functions check to see if the named check is suppressed, either
69 -- by an active scope suppress setting, or because the check has been
70 -- specifically suppressed for the given entity. If no entity is relevant
71 -- for the current check, then Empty is used as an argument. Note: the
72 -- reason we insist on specifying Empty is to force the caller to think
73 -- about whether there is any relevant entity that should be checked.
75 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean;
76 -- This function is called if Checks_May_Be_Suppressed (E) is True to
77 -- determine whether check C is suppressed either on the entity E or
78 -- as the result of a scope suppress pragma. If Checks_May_Be_Suppressed
79 -- is False, then the status of the check can be determined simply by
80 -- examining Scope_Suppress, so this routine is not called in that case.
82 function Overflow_Check_Mode return Overflow_Mode_Type;
83 -- Returns current overflow checking mode, taking into account whether
84 -- we are inside an assertion expression and the assertion policy.
86 -----------------------------------------
87 -- Control of Alignment Check Warnings --
88 -----------------------------------------
90 -- When we have address clauses, there is an issue of whether the address
91 -- specified is appropriate to the alignment. In the general case where the
92 -- address is dynamic, we generate a check and a possible warning (this
93 -- warning occurs for example if we have a restricted run time with the
94 -- restriction No_Exception_Propagation). We also issue this warning in
95 -- the case where the address is static, but we don't know the alignment
96 -- at the time we process the address clause. In such a case, we issue the
97 -- warning, but we may be able to find out later (after the back end has
98 -- annotated the actual alignment chosen) that the warning was not needed.
100 -- To deal with deleting these potentially annoying warnings, we save the
101 -- warning information in a table, and then delete the waranings in the
102 -- post compilation validation stage if we can tell that the check would
103 -- never fail (in general the back end will also optimize away the check
104 -- in such cases).
106 -- Table used to record information
108 type Alignment_Warnings_Record is record
109 E : Entity_Id;
110 -- Entity whose alignment possibly warrants a warning
112 A : Uint;
113 -- Compile time known value of address clause for which the alignment
114 -- is to be checked once we know the alignment.
116 W : Error_Msg_Id;
117 -- Id of warning message we might delete
118 end record;
120 package Alignment_Warnings is new Table.Table (
121 Table_Component_Type => Alignment_Warnings_Record,
122 Table_Index_Type => Int,
123 Table_Low_Bound => 0,
124 Table_Initial => 10,
125 Table_Increment => 200,
126 Table_Name => "Alignment_Warnings");
128 procedure Validate_Alignment_Check_Warnings;
129 -- This routine is called after back annotation of type data to delete any
130 -- alignment warnings that turn out to be false alarms, based on knowing
131 -- the actual alignment, and a compile-time known alignment value.
133 -------------------------------------------
134 -- Procedures to Activate Checking Flags --
135 -------------------------------------------
137 procedure Activate_Division_Check (N : Node_Id);
138 pragma Inline (Activate_Division_Check);
139 -- Sets Do_Division_Check flag in node N, and handles possible local raise.
140 -- Always call this routine rather than calling Set_Do_Division_Check to
141 -- set an explicit value of True, to ensure handling the local raise case.
143 procedure Activate_Overflow_Check (N : Node_Id);
144 pragma Inline (Activate_Overflow_Check);
145 -- Sets Do_Overflow_Check flag in node N, and handles possible local raise.
146 -- Always call this routine rather than calling Set_Do_Overflow_Check to
147 -- set an explicit value of True, to ensure handling the local raise case.
148 -- Note that for discrete types, this call has no effect for MOD, REM, and
149 -- unary "+" for which overflow is never possible in any case.
151 -- Note: for the discrete-type case, it is legitimate to call this routine
152 -- on an unanalyzed node where the Etype field is not set. However, for the
153 -- floating-point case, Etype must be set (to a floating-point type).
155 -- For floating-point, we set the flag if we have automatic overflow checks
156 -- on the target, or if Check_Float_Overflow mode is set. For the floating-
157 -- point case, we ignore all the unary operators ("+", "-", and abs) since
158 -- none of these can result in overflow. If there are no overflow checks on
159 -- the target, and Check_Float_Overflow mode is not set, then the call has
160 -- no effect, since in such cases we want to generate NaN's and infinities.
162 procedure Activate_Range_Check (N : Node_Id);
163 pragma Inline (Activate_Range_Check);
164 -- Sets Do_Range_Check flag in node N, and handles possible local raise
165 -- Always call this routine rather than calling Set_Do_Range_Check to
166 -- set an explicit value of True, to ensure handling the local raise case.
168 --------------------------------
169 -- Procedures to Apply Checks --
170 --------------------------------
172 -- General note on following checks. These checks are always active if
173 -- Expander_Active and not Inside_A_Generic. They are inactive and have
174 -- no effect Inside_A_Generic. In the case where not Expander_Active
175 -- and not Inside_A_Generic, most of them are inactive, but some of them
176 -- operate anyway since they may generate useful compile time warnings.
178 procedure Apply_Access_Check (N : Node_Id);
179 -- Determines whether an expression node requires a runtime access
180 -- check and if so inserts the appropriate run-time check.
182 procedure Apply_Accessibility_Check
183 (N : Node_Id;
184 Typ : Entity_Id;
185 Insert_Node : Node_Id);
186 -- Given a name N denoting an access parameter, emits a run-time
187 -- accessibility check (if necessary), checking that the level of
188 -- the object denoted by the access parameter is not deeper than the
189 -- level of the type Typ. Program_Error is raised if the check fails.
190 -- Insert_Node indicates the node where the check should be inserted.
192 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id);
193 -- E is the entity for an object which has an address clause. If checks
194 -- are enabled, then this procedure generates a check that the specified
195 -- address has an alignment consistent with the alignment of the object,
196 -- raising PE if this is not the case. The resulting check (if one is
197 -- generated) is prepended to the Actions list of N_Freeze_Entity node N.
198 -- Note that the check references E'Alignment, so it cannot be emitted
199 -- before N (its freeze node), otherwise this would cause an illegal
200 -- access before elaboration error in GIGI. For the case of a clear overlay
201 -- situation, we also check that the size of the overlaying object is not
202 -- larger than the overlaid object.
204 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id);
205 -- Handle overflow checking for an arithmetic operator. Also handles the
206 -- cases of ELIMINATED and MINIMIZED overflow checking mode. If the mode
207 -- is one of the latter two, then this routine can also be called with
208 -- an if or case expression node to make sure that we properly handle
209 -- overflow checking for dependent expressions. This routine handles
210 -- front end vs back end overflow checks (in the front end case it expands
211 -- the necessary check). Note that divide is handled separately using
212 -- Apply_Divide_Checks. Node N may or may not have Do_Overflow_Check.
213 -- In STRICT mode, there is nothing to do if this flag is off, but in
214 -- MINIMIZED/ELIMINATED mode we still have to deal with possible use
215 -- of doing operations in Long_Long_Integer or Bignum mode.
217 procedure Apply_Constraint_Check
218 (N : Node_Id;
219 Typ : Entity_Id;
220 No_Sliding : Boolean := False);
221 -- Top-level procedure, calls all the others depending on the class of
222 -- Typ. Checks that expression N satisfies the constraint of type Typ.
223 -- No_Sliding is only relevant for constrained array types, if set to
224 -- True, it checks that indexes are in range.
226 procedure Apply_Discriminant_Check
227 (N : Node_Id;
228 Typ : Entity_Id;
229 Lhs : Node_Id := Empty);
230 -- Given an expression N of a discriminated type, or of an access type
231 -- whose designated type is a discriminanted type, generates a check to
232 -- ensure that the expression can be converted to the subtype given as
233 -- the second parameter. Lhs is empty except in the case of assignments,
234 -- where the target object may be needed to determine the subtype to
235 -- check against (such as the cases of unconstrained formal parameters
236 -- and unconstrained aliased objects). For the case of unconstrained
237 -- formals, the check is performed only if the corresponding actual is
238 -- constrained, i.e., whether Lhs'Constrained is True.
240 procedure Apply_Divide_Checks (N : Node_Id);
241 -- The node kind is N_Op_Divide, N_Op_Mod, or N_Op_Rem if either of the
242 -- flags Do_Division_Check or Do_Overflow_Check is set, then this routine
243 -- ensures that the appropriate checks are made. Note that overflow can
244 -- occur in the signed case for the case of the largest negative number
245 -- divided by minus one. This procedure only applies to Integer types.
247 procedure Apply_Parameter_Aliasing_Checks
248 (Call : Node_Id;
249 Subp : Entity_Id);
250 -- Given a subprogram call Call, add a check to verify that none of the
251 -- actuals overlap. Subp denotes the subprogram being called.
253 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id);
254 -- Given a subprogram Subp, add both a pre and post condition pragmas that
255 -- verify the proper initialization of scalars in parameters and function
256 -- results.
258 procedure Apply_Predicate_Check
259 (N : Node_Id;
260 Typ : Entity_Id;
261 Fun : Entity_Id := Empty);
262 -- N is an expression to which a predicate check may need to be applied for
263 -- Typ, if Typ has a predicate function. When N is an actual in a call, Fun
264 -- is the function being called, which is used to generate a better warning
265 -- if the call leads to an infinite recursion.
267 procedure Apply_Type_Conversion_Checks (N : Node_Id);
268 -- N is an N_Type_Conversion node. A type conversion actually involves
269 -- two sorts of checks. The first check is the checks that ensures that
270 -- the operand in the type conversion fits onto the base type of the
271 -- subtype it is being converted to (see RM 4.6 (28)-(50)). The second
272 -- check is there to ensure that once the operand has been converted to
273 -- a value of the target type, this converted value meets the
274 -- constraints imposed by the target subtype (see RM 4.6 (51)).
276 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id);
277 -- The argument N is an attribute reference node intended for processing
278 -- by gigi. The attribute is one that returns a universal integer, but
279 -- the attribute reference node is currently typed with the expected
280 -- result type. This routine deals with range and overflow checks needed
281 -- to make sure that the universal result is in range.
283 function Build_Discriminant_Checks
284 (N : Node_Id;
285 T_Typ : Entity_Id)
286 return Node_Id;
287 -- Subsidiary routine for Apply_Discriminant_Check. Builds the expression
288 -- that compares discriminants of the expression with discriminants of the
289 -- type. Also used directly for membership tests (see Exp_Ch4.Expand_N_In).
291 function Convert_From_Bignum (N : Node_Id) return Node_Id;
292 -- Returns result of converting node N from Bignum. The returned value is
293 -- not analyzed, the caller takes responsibility for this. Node N must be
294 -- a subexpression node of type Bignum. The result is Long_Long_Integer.
296 function Convert_To_Bignum (N : Node_Id) return Node_Id;
297 -- Returns result of converting node N to Bignum. The returned value is not
298 -- analyzed, the caller takes responsibility for this. Node N must be a
299 -- subexpression node of a signed integer type or Bignum type (if it is
300 -- already a Bignum, the returned value is Relocate_Node (N)).
302 procedure Determine_Range
303 (N : Node_Id;
304 OK : out Boolean;
305 Lo : out Uint;
306 Hi : out Uint;
307 Assume_Valid : Boolean := False);
308 -- N is a node for a subexpression. If N is of a discrete type with no
309 -- error indications, and no other peculiarities (e.g. missing Etype),
310 -- then OK is True on return, and Lo and Hi are set to a conservative
311 -- estimate of the possible range of values of N. Thus if OK is True on
312 -- return, the value of the subexpression N is known to lie in the range
313 -- Lo .. Hi (inclusive). If the expression is not of a discrete type, or
314 -- some kind of error condition is detected, then OK is False on exit, and
315 -- Lo/Hi are set to No_Uint. Thus the significance of OK being False on
316 -- return is that no useful information is available on the range of the
317 -- expression. Assume_Valid determines whether the processing is allowed to
318 -- assume that values are in range of their subtypes. If it is set to True,
319 -- then this assumption is valid, if False, then processing is done using
320 -- base types to allow invalid values.
322 procedure Determine_Range_R
323 (N : Node_Id;
324 OK : out Boolean;
325 Lo : out Ureal;
326 Hi : out Ureal;
327 Assume_Valid : Boolean := False);
328 -- Similar to Determine_Range, but for a node N of floating-point type. OK
329 -- is True on return only for IEEE floating-point types and only if we do
330 -- not have to worry about extended precision (i.e. on the x86, we must be
331 -- using -msse2 -mfpmath=sse). At the current time, this is used only in
332 -- GNATprove, though we could consider using it more generally in future.
333 -- For that to happen, the possibility of arguments of infinite or NaN
334 -- value should be taken into account, which is not the case currently.
336 procedure Install_Null_Excluding_Check (N : Node_Id);
337 -- Determines whether an access node requires a runtime access check and
338 -- if so inserts the appropriate run-time check.
340 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id;
341 -- This function is used by top level overflow checking routines to do a
342 -- mark/release operation on the secondary stack around bignum operations.
343 -- The block created looks like:
345 -- declare
346 -- M : Mark_Id := SS_Mark;
347 -- begin
348 -- SS_Release (M);
349 -- end;
351 -- The idea is that the caller will insert any needed extra declarations
352 -- after the declaration of M, and any needed statements (in particular
353 -- the bignum operations) before the call to SS_Release, and then do an
354 -- Insert_Action of the whole block (it is returned unanalyzed). The Loc
355 -- parameter is used to supply Sloc values for the constructed tree.
357 procedure Minimize_Eliminate_Overflows
358 (N : Node_Id;
359 Lo : out Uint;
360 Hi : out Uint;
361 Top_Level : Boolean);
362 -- This is the main routine for handling MINIMIZED and ELIMINATED overflow
363 -- processing. On entry N is a node whose result is a signed integer
364 -- subtype. The Do_Overflow_Check flag may or may not be set on N. If the
365 -- node is an arithmetic operation, then a range analysis is carried out,
366 -- and there are three possibilities:
368 -- The node is left unchanged (apart from expansion of an exponentiation
369 -- operation). This happens if the routine can determine that the result
370 -- is definitely in range. The Do_Overflow_Check flag is turned off in
371 -- this case.
373 -- The node is transformed into an arithmetic operation with a result
374 -- type of Long_Long_Integer.
376 -- The node is transformed into a function call that calls an appropriate
377 -- function in the System.Bignums package to compute a Bignum result.
379 -- In the first two cases, Lo and Hi are set to the bounds of the possible
380 -- range of results, computed as accurately as possible. In the third case
381 -- Lo and Hi are set to No_Uint (there are some cases where we could get an
382 -- advantage from keeping result ranges for Bignum values, but it could use
383 -- a lot of space and is very unlikely to be valuable).
385 -- If the node is not an arithmetic operation, then it is unchanged but
386 -- Lo and Hi are still set (to the bounds of the result subtype if nothing
387 -- better can be determined).
389 -- Note: this function is recursive, if called with an arithmetic operator,
390 -- recursive calls are made to process the operands using this procedure.
391 -- So we end up doing things top down. Nothing happens to an arithmetic
392 -- expression until this procedure is called on the top level node and
393 -- then the recursive calls process all the children. We have to do it
394 -- this way. If we try to do it bottom up in natural expansion order, then
395 -- there are two problems. First, where do we stash the bounds, and more
396 -- importantly, semantic processing will be messed up. Consider A+B+C where
397 -- A,B,C are all of type integer, if we processed A+B before doing semantic
398 -- analysis of the addition of this result to C, that addition could end up
399 -- with a Long_Long_Integer left operand and an Integer right operand, and
400 -- we would get a semantic error.
402 -- The routine is called in three situations if we are operating in either
403 -- MINIMIZED or ELIMINATED modes.
405 -- Overflow processing applied to the top node of an expression tree when
406 -- that node is an arithmetic operator. In this case the result is
407 -- converted to the appropriate result type (there is special processing
408 -- when the parent is a conversion, see body for details).
410 -- Overflow processing applied to the operands of a comparison operation.
411 -- In this case, the comparison is done on the result Long_Long_Integer
412 -- or Bignum values, without raising any exceptions.
414 -- Overflow processing applied to the left operand of a membership test.
415 -- In this case no exception is raised if a Long_Long_Integer or Bignum
416 -- result is outside the range of the type of that left operand (it is
417 -- just that the result of IN is false in that case).
419 -- Note that if Bignum values appear, the caller must take care of doing
420 -- the appropriate mark/release operations on the secondary stack.
422 -- Top_Level is used to avoid inefficient unnecessary transitions into the
423 -- Bignum domain. If Top_Level is True, it means that the caller will have
424 -- to convert any Bignum value back to Long_Long_Integer, possibly checking
425 -- that the value is in range. This is the normal case for a top level
426 -- operator in a subexpression. There is no point in going into Bignum mode
427 -- to avoid an overflow just so we can check for overflow the next moment.
428 -- For calls from comparisons and membership tests, and for all recursive
429 -- calls, we do want to transition into the Bignum domain if necessary.
430 -- Note that this setting is only relevant in ELIMINATED mode.
432 -------------------------------------------------------
433 -- Control and Optimization of Range/Overflow Checks --
434 -------------------------------------------------------
436 -- Range checks are controlled by the Do_Range_Check flag. The front end
437 -- is responsible for setting this flag in relevant nodes. Originally
438 -- the back end generated all corresponding range checks. But later on
439 -- we decided to generate many range checks in the front end. We are now
440 -- in the transitional phase where some of these checks are still done
441 -- by the back end, but many are done by the front end. It is possible
442 -- that in the future we might move all the checks to the front end. The
443 -- main remaining back end checks are for subscript checking.
445 -- Overflow checks are similarly controlled by the Do_Overflow_Check flag.
446 -- The difference here is that if back end overflow checks are inactive
447 -- (Backend_Overflow_Checks_On_Target set False), then the actual overflow
448 -- checks are generated by the front end, but if back end overflow checks
449 -- are active (Backend_Overflow_Checks_On_Target set True), then the back
450 -- end does generate the checks.
452 -- The following two routines are used to set these flags, they allow
453 -- for the possibility of eliminating checks. Checks can be eliminated
454 -- if an identical check has already been performed.
456 procedure Enable_Overflow_Check (N : Node_Id);
457 -- First this routine determines if an overflow check is needed by doing
458 -- an appropriate range check. If a check is not needed, then the call
459 -- has no effect. If a check is needed then this routine sets the flag
460 -- Do_Overflow_Check in node N to True, unless it can be determined that
461 -- the check is not needed. The only condition under which this is the
462 -- case is if there was an identical check earlier on.
464 procedure Enable_Range_Check (N : Node_Id);
465 -- Set Do_Range_Check flag in node N True, unless it can be determined
466 -- that the check is not needed. The only condition under which this is
467 -- the case is if there was an identical check earlier on. This routine
468 -- is not responsible for doing range analysis to determine whether or
469 -- not such a check is needed -- the caller is expected to do this. The
470 -- one other case in which the request to set the flag is ignored is
471 -- when Kill_Range_Check is set in an N_Unchecked_Conversion node.
473 -- The following routines are used to keep track of processing sequences
474 -- of statements (e.g. the THEN statements of an IF statement). A check
475 -- that appears within such a sequence can eliminate an identical check
476 -- within this sequence of statements. However, after the end of the
477 -- sequence of statements, such a check is no longer of interest, since
478 -- it may not have been executed.
480 procedure Conditional_Statements_Begin;
481 -- This call marks the start of processing of a sequence of statements.
482 -- Every call to this procedure must be followed by a matching call to
483 -- Conditional_Statements_End.
485 procedure Conditional_Statements_End;
486 -- This call removes from consideration all saved checks since the
487 -- corresponding call to Conditional_Statements_Begin. These two
488 -- procedures operate in a stack like manner.
490 -- The mechanism for optimizing checks works by remembering checks
491 -- that have already been made, but certain conditions, for example
492 -- an assignment to a variable involved in a check, may mean that the
493 -- remembered check is no longer valid, in the sense that if the same
494 -- expression appears again, another check is required because the
495 -- value may have changed.
497 -- The following routines are used to note conditions which may render
498 -- some or all of the stored and remembered checks to be invalidated.
500 procedure Kill_Checks (V : Entity_Id);
501 -- This procedure records an assignment or other condition that causes
502 -- the value of the variable to be changed, invalidating any stored
503 -- checks that reference the value. Note that all such checks must
504 -- be discarded, even if they are not in the current statement range.
506 procedure Kill_All_Checks;
507 -- This procedure kills all remembered checks
509 -----------------------------
510 -- Length and Range Checks --
511 -----------------------------
513 -- In the following procedures, there are three arguments which have
514 -- a common meaning as follows:
516 -- Expr The expression to be checked. If a check is required,
517 -- the appropriate flag will be placed on this node. Whether
518 -- this node is further examined depends on the setting of
519 -- the parameter Source_Typ, as described below.
521 -- ??? Apply_Length_Check and Apply_Range_Check do not have an Expr
522 -- formal
524 -- ??? Apply_Length_Check and Apply_Range_Check have a Ck_Node formal
525 -- which is undocumented, is it the same as Expr?
527 -- Target_Typ The target type on which the check is to be based. For
528 -- example, if we have a scalar range check, then the check
529 -- is that we are in range of this type.
531 -- Source_Typ Normally Empty, but can be set to a type, in which case
532 -- this type is used for the check, see below.
534 -- The checks operate in one of two modes:
536 -- If Source_Typ is Empty, then the node Expr is examined, at the very
537 -- least to get the source subtype. In addition for some of the checks,
538 -- the actual form of the node may be examined. For example, a node of
539 -- type Integer whose actual form is an Integer conversion from a type
540 -- with range 0 .. 3 can be determined to have a value in range 0 .. 3.
542 -- If Source_Typ is given, then nothing can be assumed about the Expr,
543 -- and indeed its contents are not examined. In this case the check is
544 -- based on the assumption that Expr can be an arbitrary value of the
545 -- given Source_Typ.
547 -- Currently, the only case in which a Source_Typ is explicitly supplied
548 -- is for the case of Out and In_Out parameters, where, for the conversion
549 -- on return (the Out direction), the types must be reversed. This is
550 -- handled by the caller.
552 procedure Apply_Length_Check
553 (Ck_Node : Node_Id;
554 Target_Typ : Entity_Id;
555 Source_Typ : Entity_Id := Empty);
556 -- This procedure builds a sequence of declarations to do a length check
557 -- that checks if the lengths of the two arrays Target_Typ and source type
558 -- are the same. The resulting actions are inserted at Node using a call
559 -- to Insert_Actions.
561 -- For access types, the Directly_Designated_Type is retrieved and
562 -- processing continues as enumerated above, with a guard against null
563 -- values.
565 -- Note: calls to Apply_Length_Check currently never supply an explicit
566 -- Source_Typ parameter, but Apply_Length_Check takes this parameter and
567 -- processes it as described above for consistency with the other routines
568 -- in this section.
570 procedure Apply_Range_Check
571 (Ck_Node : Node_Id;
572 Target_Typ : Entity_Id;
573 Source_Typ : Entity_Id := Empty);
574 -- For a Node of kind N_Range, constructs a range check action that tests
575 -- first that the range is not null and then that the range is contained in
576 -- the Target_Typ range.
578 -- For scalar types, constructs a range check action that first tests that
579 -- the expression is contained in the Target_Typ range. The difference
580 -- between this and Apply_Scalar_Range_Check is that the latter generates
581 -- the actual checking code against the Etype of the expression.
583 -- For constrained array types, construct series of range check actions
584 -- to check that each Expr range is properly contained in the range of
585 -- Target_Typ.
587 -- For a type conversion to an unconstrained array type, constructs a range
588 -- check action to check that the bounds of the source type are within the
589 -- constraints imposed by the Target_Typ.
591 -- For access types, the Directly_Designated_Type is retrieved and
592 -- processing continues as enumerated above, with a guard against null
593 -- values.
595 -- The source type is used by type conversions to unconstrained array
596 -- types to retrieve the corresponding bounds.
598 procedure Apply_Static_Length_Check
599 (Expr : Node_Id;
600 Target_Typ : Entity_Id;
601 Source_Typ : Entity_Id := Empty);
602 -- Tries to determine statically whether the two array types source type
603 -- and Target_Typ have the same length. If it can be determined at compile
604 -- time that they do not, then an N_Raise_Constraint_Error node replaces
605 -- Expr, and a warning message is issued.
607 procedure Apply_Scalar_Range_Check
608 (Expr : Node_Id;
609 Target_Typ : Entity_Id;
610 Source_Typ : Entity_Id := Empty;
611 Fixed_Int : Boolean := False);
612 -- For scalar types, determines whether an expression node should be
613 -- flagged as needing a runtime range check. If the node requires such a
614 -- check, the Do_Range_Check flag is turned on. The Fixed_Int flag if set
615 -- causes any fixed-point values to be treated as though they were discrete
616 -- values (i.e. the underlying integer value is used).
618 type Check_Result is private;
619 -- Type used to return result of Get_Range_Checks call, for later use in
620 -- call to Insert_Range_Checks procedure.
622 function Get_Range_Checks
623 (Ck_Node : Node_Id;
624 Target_Typ : Entity_Id;
625 Source_Typ : Entity_Id := Empty;
626 Warn_Node : Node_Id := Empty) return Check_Result;
627 -- Like Apply_Range_Check, except it does not modify anything. Instead
628 -- it returns an encapsulated result of the check operations for later
629 -- use in a call to Insert_Range_Checks. If Warn_Node is non-empty, its
630 -- Sloc is used, in the static case, for the generated warning or error.
631 -- Additionally, it is used rather than Expr (or Low/High_Bound of Expr)
632 -- in constructing the check.
634 procedure Append_Range_Checks
635 (Checks : Check_Result;
636 Stmts : List_Id;
637 Suppress_Typ : Entity_Id;
638 Static_Sloc : Source_Ptr;
639 Flag_Node : Node_Id);
640 -- Called to append range checks as returned by a call to Get_Range_Checks.
641 -- Stmts is a list to which either the dynamic check is appended or the
642 -- raise Constraint_Error statement is appended (for static checks).
643 -- Static_Sloc is the Sloc at which the raise CE node points, Flag_Node is
644 -- used as the node at which to set the Has_Dynamic_Check flag. Checks_On
645 -- is a boolean value that says if range and index checking is on or not.
647 procedure Insert_Range_Checks
648 (Checks : Check_Result;
649 Node : Node_Id;
650 Suppress_Typ : Entity_Id;
651 Static_Sloc : Source_Ptr := No_Location;
652 Flag_Node : Node_Id := Empty;
653 Do_Before : Boolean := False);
654 -- Called to insert range checks as returned by a call to Get_Range_Checks.
655 -- Node is the node after which either the dynamic check is inserted or
656 -- the raise Constraint_Error statement is inserted (for static checks).
657 -- Suppress_Typ is the type to check to determine if checks are suppressed.
658 -- Static_Sloc, if passed, is the Sloc at which the raise CE node points,
659 -- otherwise Sloc (Node) is used. The Has_Dynamic_Check flag is normally
660 -- set at Node. If Flag_Node is present, then this is used instead as the
661 -- node at which to set the Has_Dynamic_Check flag. Normally the check is
662 -- inserted after, if Do_Before is True, the check is inserted before
663 -- Node.
665 -----------------------
666 -- Expander Routines --
667 -----------------------
669 -- Some of the earlier processing for checks results in temporarily setting
670 -- the Do_Range_Check flag rather than actually generating checks. Now we
671 -- are moving the generation of such checks into the front end for reasons
672 -- of efficiency and simplicity (there were difficulties in handling this
673 -- in the back end when side effects were present in the expressions being
674 -- checked).
676 -- Probably we could eliminate the Do_Range_Check flag entirely and
677 -- generate the checks earlier, but this is a delicate area and it
678 -- seemed safer to implement the following routines, which are called
679 -- late on in the expansion process. They check the Do_Range_Check flag
680 -- and if it is set, generate the actual checks and reset the flag.
682 procedure Generate_Range_Check
683 (N : Node_Id;
684 Target_Type : Entity_Id;
685 Reason : RT_Exception_Code);
686 -- This procedure is called to actually generate and insert a range check.
687 -- A check is generated to ensure that the value of N lies within the range
688 -- of the target type. Note that the base type of N may be different from
689 -- the base type of the target type. This happens in the conversion case.
690 -- The Reason parameter is the exception code to be used for the exception
691 -- if raised.
693 -- Note: if the expander is not active, or if we are in GNATprove mode,
694 -- then we do not generate explicit range code. Instead we just turn the
695 -- Do_Range_Check flag on, since in these cases that's what we want to see
696 -- in the tree (GNATprove in particular depends on this flag being set). If
697 -- we generate the actual range check, then we make sure the flag is off,
698 -- since the code we generate takes complete care of the check.
700 -- Historical note: We used to just pass on the Do_Range_Check flag to the
701 -- back end to generate the check, but now in code-generation mode we never
702 -- have this flag set, since the front end takes care of the check. The
703 -- normal processing flow now is that the analyzer typically turns on the
704 -- Do_Range_Check flag, and if it is set, this routine is called, which
705 -- turns the flag off in code-generation mode.
707 procedure Generate_Index_Checks (N : Node_Id);
708 -- This procedure is called to generate index checks on the subscripts for
709 -- the indexed component node N. Each subscript expression is examined, and
710 -- if the Do_Range_Check flag is set, an appropriate index check is
711 -- generated and the flag is reset.
713 -- Similarly, we set the flag Do_Discriminant_Check in the semantic
714 -- analysis to indicate that a discriminant check is required for selected
715 -- component of a discriminated type. The following routine is called from
716 -- the expander to actually generate the call.
718 procedure Generate_Discriminant_Check (N : Node_Id);
719 -- N is a selected component for which a discriminant check is required to
720 -- make sure that the discriminants have appropriate values for the
721 -- selection. This is done by calling the appropriate discriminant checking
722 -- routine for the selector.
724 -----------------------
725 -- Validity Checking --
726 -----------------------
728 -- In (RM 13.9.1(9-11)) we have the following rules on invalid values
730 -- If the representation of a scalar object does not represent value of
731 -- the object's subtype (perhaps because the object was not initialized),
732 -- the object is said to have an invalid representation. It is a bounded
733 -- error to evaluate the value of such an object. If the error is
734 -- detected, either Constraint_Error or Program_Error is raised.
735 -- Otherwise, execution continues using the invalid representation. The
736 -- rules of the language outside this subclause assume that all objects
737 -- have valid representations. The semantics of operations on invalid
738 -- representations are as follows:
740 -- 10 If the representation of the object represents a value of the
741 -- object's type, the value of the type is used.
743 -- 11 If the representation of the object does not represent a value
744 -- of the object's type, the semantics of operations on such
745 -- representations is implementation-defined, but does not by
746 -- itself lead to erroneous or unpredictable execution, or to
747 -- other objects becoming abnormal.
749 -- We quote the rules in full here since they are quite delicate. Most
750 -- of the time, we can just compute away with wrong values, and get a
751 -- possibly wrong result, which is well within the range of allowed
752 -- implementation defined behavior. The two tricky cases are subscripted
753 -- array assignments, where we don't want to do wild stores, and case
754 -- statements where we don't want to do wild jumps.
756 -- In GNAT, we control validity checking with a switch -gnatV that can take
757 -- three parameters, n/d/f for None/Default/Full. These modes have the
758 -- following meanings:
760 -- None (no validity checking)
762 -- In this mode, there is no specific checking for invalid values
763 -- and the code generator assumes that all stored values are always
764 -- within the bounds of the object subtype. The consequences are as
765 -- follows:
767 -- For case statements, an out of range invalid value will cause
768 -- Constraint_Error to be raised, or an arbitrary one of the case
769 -- alternatives will be executed. Wild jumps cannot result even
770 -- in this mode, since we always do a range check
772 -- For subscripted array assignments, wild stores will result in
773 -- the expected manner when addresses are calculated using values
774 -- of subscripts that are out of range.
776 -- It could perhaps be argued that this mode is still conformant with
777 -- the letter of the RM, since implementation defined is a rather
778 -- broad category, but certainly it is not in the spirit of the
779 -- RM requirement, since wild stores certainly seem to be a case of
780 -- erroneous behavior.
782 -- Default (default standard RM-compatible validity checking)
784 -- In this mode, which is the default, minimal validity checking is
785 -- performed to ensure no erroneous behavior as follows:
787 -- For case statements, an out of range invalid value will cause
788 -- Constraint_Error to be raised.
790 -- For subscripted array assignments, invalid out of range
791 -- subscript values will cause Constraint_Error to be raised.
793 -- Full (Full validity checking)
795 -- In this mode, the protections guaranteed by the standard mode are
796 -- in place, and the following additional checks are made:
798 -- For every assignment, the right side is checked for validity
800 -- For every call, IN and IN OUT parameters are checked for validity
802 -- For every subscripted array reference, both for stores and loads,
803 -- all subscripts are checked for validity.
805 -- These checks are not required by the RM, but will in practice
806 -- improve the detection of uninitialized variables, particularly
807 -- if used in conjunction with pragma Normalize_Scalars.
809 -- In the above description, we talk about performing validity checks,
810 -- but we don't actually generate a check in a case where the compiler
811 -- can be sure that the value is valid. Note that this assurance must
812 -- be achieved without assuming that any uninitialized value lies within
813 -- the range of its type. The following are cases in which values are
814 -- known to be valid. The flag Is_Known_Valid is used to keep track of
815 -- some of these cases.
817 -- If all possible stored values are valid, then any uninitialized
818 -- value must be valid.
820 -- Literals, including enumeration literals, are clearly always valid
822 -- Constants are always assumed valid, with a validity check being
823 -- performed on the initializing value where necessary to ensure that
824 -- this is the case.
826 -- For variables, the status is set to known valid if there is an
827 -- initializing expression. Again a check is made on the initializing
828 -- value if necessary to ensure that this assumption is valid. The
829 -- status can change as a result of local assignments to a variable.
830 -- If a known valid value is unconditionally assigned, then we mark
831 -- the left side as known valid. If a value is assigned that is not
832 -- known to be valid, then we mark the left side as invalid. This
833 -- kind of processing does NOT apply to non-local variables since we
834 -- are not following the flow graph (more properly the flow of actual
835 -- processing only corresponds to the flow graph for local assignments).
836 -- For non-local variables, we preserve the current setting, i.e. a
837 -- validity check is performed when assigning to a knonwn valid global.
839 -- Note: no validity checking is required if range checks are suppressed
840 -- regardless of the setting of the validity checking mode.
842 -- The following procedures are used in handling validity checking
844 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id);
845 -- Expr is the node for an indexed component. If validity checking and
846 -- range checking are enabled, all subscripts for this indexed component
847 -- are checked for validity.
849 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id);
850 -- Expr is a lvalue, i.e. an expression representing the target of an
851 -- assignment. This procedure checks for this expression involving an
852 -- assignment to an array value. We have to be sure that all the subscripts
853 -- in such a case are valid, since according to the rules in (RM
854 -- 13.9.1(9-11)) such assignments are not permitted to result in erroneous
855 -- behavior in the case of invalid subscript values.
857 procedure Ensure_Valid
858 (Expr : Node_Id;
859 Holes_OK : Boolean := False;
860 Related_Id : Entity_Id := Empty;
861 Is_Low_Bound : Boolean := False;
862 Is_High_Bound : Boolean := False);
863 -- Ensure that Expr represents a valid value of its type. If this type
864 -- is not a scalar type, then the call has no effect, since validity
865 -- is only an issue for scalar types. The effect of this call is to
866 -- check if the value is known valid, if so, nothing needs to be done.
867 -- If this is not known, then either Expr is set to be range checked,
868 -- or specific checking code is inserted so that an exception is raised
869 -- if the value is not valid.
871 -- The optional argument Holes_OK indicates whether it is necessary to
872 -- worry about enumeration types with non-standard representations leading
873 -- to "holes" in the range of possible representations. If Holes_OK is
874 -- True, then such values are assumed valid (this is used when the caller
875 -- will make a separate check for this case anyway). If Holes_OK is False,
876 -- then this case is checked, and code is inserted to ensure that Expr is
877 -- valid, raising Constraint_Error if the value is not valid.
879 -- Related_Id denotes the entity of the context where Expr appears. Flags
880 -- Is_Low_Bound and Is_High_Bound specify whether the expression to check
881 -- is the low or the high bound of a range. These three optional arguments
882 -- signal Remove_Side_Effects to create an external symbol of the form
883 -- Chars (Related_Id)_FIRST/_LAST. For suggested use of these parameters
884 -- see the warning in the body of Sem_Ch3.Process_Range_Expr_In_Decl.
886 function Expr_Known_Valid (Expr : Node_Id) return Boolean;
887 -- This function tests it the value of Expr is known to be valid in the
888 -- sense of RM 13.9.1(9-11). In the case of GNAT, it is only discrete types
889 -- which are a concern, since for non-discrete types we simply continue
890 -- computation with invalid values, which does not lead to erroneous
891 -- behavior. Thus Expr_Known_Valid always returns True if the type of Expr
892 -- is non-discrete. For discrete types the value returned is True only if
893 -- it can be determined that the value is Valid. Otherwise False is
894 -- returned.
896 procedure Insert_Valid_Check
897 (Expr : Node_Id;
898 Related_Id : Entity_Id := Empty;
899 Is_Low_Bound : Boolean := False;
900 Is_High_Bound : Boolean := False);
901 -- Inserts code that will check for the value of Expr being valid, in the
902 -- sense of the 'Valid attribute returning True. Constraint_Error will be
903 -- raised if the value is not valid.
905 -- Related_Id denotes the entity of the context where Expr appears. Flags
906 -- Is_Low_Bound and Is_High_Bound specify whether the expression to check
907 -- is the low or the high bound of a range. These three optional arguments
908 -- signal Remove_Side_Effects to create an external symbol of the form
909 -- Chars (Related_Id)_FIRST/_LAST. For suggested use of these parameters
910 -- see the warning in the body of Sem_Ch3.Process_Range_Expr_In_Decl.
912 procedure Null_Exclusion_Static_Checks (N : Node_Id);
913 -- Ada 2005 (AI-231): Check bad usages of the null-exclusion issue
915 procedure Remove_Checks (Expr : Node_Id);
916 -- Remove all checks from Expr except those that are only executed
917 -- conditionally (on the right side of And Then/Or Else. This call
918 -- removes only embedded checks (Do_Range_Check, Do_Overflow_Check).
920 procedure Validity_Check_Range
921 (N : Node_Id;
922 Related_Id : Entity_Id := Empty);
923 -- If N is an N_Range node, then Ensure_Valid is called on its bounds, if
924 -- validity checking of operands is enabled. Related_Id denotes the entity
925 -- of the context where N appears.
927 -----------------------------
928 -- Handling of Check Names --
929 -----------------------------
931 -- The following table contains Name_Id's for recognized checks. The first
932 -- entries (corresponding to the values of the subtype Predefined_Check_Id)
933 -- contain the Name_Id values for the checks that are predefined, including
934 -- All_Checks (see Types). Remaining entries are those that are introduced
935 -- by pragma Check_Names.
937 package Check_Names is new Table.Table (
938 Table_Component_Type => Name_Id,
939 Table_Index_Type => Check_Id,
940 Table_Low_Bound => 1,
941 Table_Initial => 30,
942 Table_Increment => 200,
943 Table_Name => "Name_Check_Names");
945 function Get_Check_Id (N : Name_Id) return Check_Id;
946 -- Function to search above table for matching name. If found returns the
947 -- corresponding Check_Id value in the range 1 .. Check_Name.Last. If not
948 -- found returns No_Check_Id.
950 private
952 type Check_Result is array (Positive range 1 .. 2) of Node_Id;
953 -- There are two cases for the result returned by Range_Check:
955 -- For the static case the result is one or two nodes that should cause
956 -- a Constraint_Error. Typically these will include Expr itself or the
957 -- direct descendants of Expr, such as Low/High_Bound (Expr)). It is the
958 -- responsibility of the caller to rewrite and substitute the nodes with
959 -- N_Raise_Constraint_Error nodes.
961 -- For the non-static case a single N_Raise_Constraint_Error node with a
962 -- non-empty Condition field is returned.
964 -- Unused entries in Check_Result, if any, are simply set to Empty For
965 -- external clients, the required processing on this result is achieved
966 -- using the Insert_Range_Checks routine.
968 pragma Inline (Apply_Length_Check);
969 pragma Inline (Apply_Range_Check);
970 pragma Inline (Apply_Static_Length_Check);
971 end Checks;