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-2002 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 2,  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 COPYING.  If not, write --
19-- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
20-- MA 02111-1307, USA.                                                      --
21--                                                                          --
22-- GNAT was originally developed  by the GNAT team at  New York University. --
23-- Extensive contributions were provided by Ada Core Technologies Inc.      --
24--                                                                          --
25------------------------------------------------------------------------------
26
27--  Package containing routines used to deal with runtime checks. These
28--  routines are used both by the semantics and by the expander. In some
29--  cases, checks are enabled simply by setting flags for gigi, and in
30--  other cases the code for the check is expanded.
31
32--  The approach used for range and length checks, in regards to suppressed
33--  checks, is to attempt to detect at compilation time that a constraint
34--  error will occur. If this is detected a warning or error is issued and the
35--  offending expression or statement replaced with a constraint error node.
36--  This always occurs whether checks are suppressed or not.  Dynamic range
37--  checks are, of course, not inserted if checks are suppressed.
38
39with Types; use Types;
40with Uintp; use Uintp;
41
42package Checks is
43
44   procedure Initialize;
45   --  Called for each new main source program, to initialize internal
46   --  variables used in the package body of the Checks unit.
47
48   function Access_Checks_Suppressed        (E : Entity_Id) return Boolean;
49   function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean;
50   function Discriminant_Checks_Suppressed  (E : Entity_Id) return Boolean;
51   function Division_Checks_Suppressed      (E : Entity_Id) return Boolean;
52   function Elaboration_Checks_Suppressed   (E : Entity_Id) return Boolean;
53   function Index_Checks_Suppressed         (E : Entity_Id) return Boolean;
54   function Length_Checks_Suppressed        (E : Entity_Id) return Boolean;
55   function Overflow_Checks_Suppressed      (E : Entity_Id) return Boolean;
56   function Range_Checks_Suppressed         (E : Entity_Id) return Boolean;
57   function Storage_Checks_Suppressed       (E : Entity_Id) return Boolean;
58   function Tag_Checks_Suppressed           (E : Entity_Id) return Boolean;
59   --  These functions check to see if the named check is suppressed,
60   --  either by an active scope suppress setting, or because the check
61   --  has been specifically suppressed for the given entity. If no entity
62   --  is relevant for the current check, then Empty is used as an argument.
63   --  Note: the reason we insist on specifying Empty is to force the
64   --  caller to think about whether there is any relevant entity that
65   --  should be checked.
66
67   --  General note on following checks. These checks are always active if
68   --  Expander_Active and not Inside_A_Generic. They are inactive and have
69   --  no effect Inside_A_Generic. In the case where not Expander_Active
70   --  and not Inside_A_Generic, most of them are inactive, but some of them
71   --  operate anyway since they may generate useful compile time warnings.
72
73   procedure Apply_Access_Check (N : Node_Id);
74   --  Determines whether an expression node requires a runtime access
75   --  check and if so inserts the appropriate run-time check.
76
77   procedure Apply_Accessibility_Check (N : Node_Id; Typ : Entity_Id);
78   --  Given a name N denoting an access parameter, emits a run-time
79   --  accessibility check (if necessary), checking that the level of
80   --  the object denoted by the access parameter is not deeper than the
81   --  level of the type Typ. Program_Error is raised if the check fails.
82
83   procedure Apply_Alignment_Check (E : Entity_Id; N : Node_Id);
84   --  E is the entity for an object. If there is an address clause for
85   --  this entity, and checks are enabled, then this procedure generates
86   --  a check that the specified address has an alignment consistent with
87   --  the alignment of the object, raising PE if this is not the case. The
88   --  resulting check (if one is generated) is inserted before node N.
89
90   procedure Apply_Array_Size_Check (N : Node_Id; Typ : Entity_Id);
91   --  N is the node for an object declaration that declares an object of
92   --  array type Typ. This routine generates, if necessary, a check that
93   --  the size of the array is not too large, raising Storage_Error if so.
94
95   procedure Apply_Arithmetic_Overflow_Check (N : Node_Id);
96   --  Given a binary arithmetic operator (+ - *) expand a software integer
97   --  overflow check using range checks on a larger checking type or a call
98   --  to an appropriate runtime routine. This is used for all three operators
99   --  for the signed integer case, and for +/- in the fixed-point case. The
100   --  check is expanded only if Software_Overflow_Checking is enabled and
101   --  Do_Overflow_Check is set on node N. Note that divide is handled
102   --  separately using Apply_Arithmetic_Divide_Overflow_Check.
103
104   procedure Apply_Constraint_Check
105     (N          : Node_Id;
106      Typ        : Entity_Id;
107      No_Sliding : Boolean := False);
108   --  Top-level procedure, calls all the others depending on the class of Typ.
109   --  Checks that expression N verifies the constraint of type Typ. No_Sliding
110   --  is only relevant for constrained array types, id set to true, it
111   --  checks that indexes are in range.
112
113   procedure Apply_Discriminant_Check
114     (N   : Node_Id;
115      Typ : Entity_Id;
116      Lhs : Node_Id := Empty);
117   --  Given an expression N of a discriminated type, or of an access type
118   --  whose designated type is a discriminanted type, generates a check to
119   --  ensure that the expression can be converted to the subtype given as
120   --  the second parameter. Lhs is empty except in the case of assignments,
121   --  where the target object may be needed to determine the subtype to
122   --  check against (such as the cases of unconstrained formal parameters
123   --  and unconstrained aliased objects). For the case of unconstrained
124   --  formals, the check is peformed only if the corresponding actual is
125   --  constrained, i.e., whether Lhs'Constrained is True.
126
127   function Build_Discriminant_Checks
128     (N     : Node_Id;
129      T_Typ : Entity_Id)
130      return  Node_Id;
131   --  Subsidiary routine for Apply_Discriminant_Check. Builds the expression
132   --  that compares discriminants of the expression with discriminants of the
133   --  type. Also used directly for membership tests (see Exp_Ch4.Expand_N_In).
134
135   procedure Apply_Divide_Check (N : Node_Id);
136   --  The node kind is N_Op_Divide, N_Op_Mod, or N_Op_Rem. An appropriate
137   --  check is generated to ensure that the right operand is non-zero. In
138   --  the divide case, we also check that we do not have the annoying case
139   --  of the largest negative number divided by minus one.
140
141   procedure Apply_Type_Conversion_Checks (N : Node_Id);
142   --  N is an N_Type_Conversion node. A type conversion actually involves
143   --  two sorts of checks. The first check is the checks that ensures that
144   --  the operand in the type conversion fits onto the base type of the
145   --  subtype it is being converted to (see RM 4.6 (28)-(50)). The second
146   --  check is there to ensure that once the operand has been converted to
147   --  a value of the target type, this converted value meets the
148   --  constraints imposed by the target subtype (see RM 4.6 (51)).
149
150   procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id);
151   --  The argument N is an attribute reference node intended for processing
152   --  by gigi. The attribute is one that returns a universal integer, but
153   --  the attribute reference node is currently typed with the expected
154   --  result type. This routine deals with range and overflow checks needed
155   --  to make sure that the universal result is in range.
156
157   procedure Determine_Range
158     (N  : Node_Id;
159      OK : out Boolean;
160      Lo : out Uint;
161      Hi : out Uint);
162   --  N is a node for a subexpression. If N is of a discrete type with
163   --  no error indications, and no other peculiarities (e.g. missing
164   --  type fields), then OK is True on return, and Lo and Hi are set
165   --  to a conservative estimate of the possible range of values of N.
166   --  Thus if OK is True on return, the value of the subexpression N is
167   --  known to like in the range Lo .. Hi (inclusive). If the expression
168   --  is not of a discrete type, or some kind of error condition is
169   --  detected, then OK is False on exit, and Lo/Hi are set to No_Uint.
170   --  Thus the significance of OK being False on return is that no
171   --  useful information is available on the range of the expression.
172
173   -------------------------------------------------------
174   -- Control and Optimization of Range/Overflow Checks --
175   -------------------------------------------------------
176
177   --  Range checks are controlled by the Do_Range_Check flag. The front end
178   --  is responsible for setting this flag in relevant nodes. Originally
179   --  the back end generated all corresponding range checks. But later on
180   --  we decided to generate all range checks in the front end. We are now
181   --  in the transitional phase where some of these checks are still done
182   --  by the back end, but many are done by the front end.
183
184   --  Overflow checks are similarly controlled by the Do_Overflow_Check
185   --  flag. The difference here is that if Backend_Overflow_Checks is
186   --  is (Backend_Overflow_Checks_On_Target set False), then the actual
187   --  overflow checks are generated by the front end, but if back end
188   --  overflow checks are active (Backend_Overflow_Checks_On_Target
189   --  set True), then the back end does generate the checks.
190
191   --  The following two routines are used to set these flags, they allow
192   --  for the possibility of eliminating checks. Checks can be eliminated
193   --  if an identical check has already been performed.
194
195   procedure Enable_Overflow_Check (N : Node_Id);
196   --  First this routine determines if an overflow check is needed by doing
197   --  an appropriate range check. If a check is not needed, then the call
198   --  has no effect. If a check is needed then this routine sets the flag
199   --  Set Do_Overflow_Check in node N to True, unless it can be determined
200   --  that the check is not needed. The only condition under which this is
201   --  the case is if there was an identical check earlier on.
202
203   procedure Enable_Range_Check (N : Node_Id);
204   --  Set Do_Range_Check flag in node N True, unless it can be determined
205   --  that the check is not needed. The only condition under which this is
206   --  the case is if there was an identical check earlier on. This routine
207   --  is not responsible for doing range analysis to determine whether or
208   --  not such a check is needed -- the caller is expected to do this. The
209   --  one other case in which the request to set the flag is ignored is
210   --  when Kill_Range_Check is set in an N_Unchecked_Conversion node.
211
212   --  The following routines are used to keep track of processing sequences
213   --  of statements (e.g. the THEN statements of an IF statement). A check
214   --  that appears within such a sequence can eliminate an identical check
215   --  within this sequence of statements. However, after the end of the
216   --  sequence of statements, such a check is no longer of interest, since
217   --  it may not have been executed.
218
219   procedure Conditional_Statements_Begin;
220   --  This call marks the start of processing of a sequence of statements.
221   --  Every call to this procedure must be followed by a matching call to
222   --  Conditional_Statements_End.
223
224   procedure Conditional_Statements_End;
225   --  This call removes from consideration all saved checks since the
226   --  corresponding call to Conditional_Statements_Begin. These two
227   --  procedures operate in a stack like manner.
228
229   --  The mechanism for optimizing checks works by remembering checks
230   --  that have already been made, but certain conditions, for example
231   --  an assignment to a variable involved in a check, may mean that the
232   --  remembered check is no longer valid, in the sense that if the same
233   --  expression appears again, another check is required because the
234   --  value may have changed.
235
236   --  The following routines are used to note conditions which may render
237   --  some or all of the stored and remembered checks to be invalidated.
238
239   procedure Kill_Checks (V : Entity_Id);
240   --  This procedure records an assignment or other condition that causes
241   --  the value of the variable to be changed, invalidating any stored
242   --  checks that reference the value. Note that all such checks must
243   --  be discarded, even if they are not in the current statement range.
244
245   procedure Kill_All_Checks;
246   --  This procedure kills all remembered checks.
247
248   -----------------------------
249   -- Length and Range Checks --
250   -----------------------------
251
252   --  In the following procedures, there are three arguments which have
253   --  a common meaning as follows:
254
255   --    Expr        The expression to be checked. If a check is required,
256   --                the appropriate flag will be placed on this node. Whether
257   --                this node is further examined depends on the setting of
258   --                the parameter Source_Typ, as described below.
259
260   --    Target_Typ  The target type on which the check is to be based. For
261   --                example, if we have a scalar range check, then the check
262   --                is that we are in range of this type.
263
264   --    Source_Typ  Normally Empty, but can be set to a type, in which case
265   --                this type is used for the check, see below.
266
267   --  The checks operate in one of two modes:
268
269   --    If Source_Typ is Empty, then the node Expr is examined, at the
270   --    very least to get the source subtype. In addition for some of
271   --    the checks, the actual form of the node may be examined. For
272   --    example, a node of type Integer whose actual form is an Integer
273   --    conversion from a type with range 0 .. 3 can be determined to
274   --    have a value in the range 0 .. 3.
275
276   --    If Source_Typ is given, then nothing can be assumed about the
277   --    Expr, and indeed its contents are not examined. In this case the
278   --    check is based on the assumption that Expr can be an arbitrary
279   --    value of the given Source_Typ.
280
281   --  Currently, the only case in which a Source_Typ is explicitly supplied
282   --  is for the case of Out and In_Out parameters, where, for the conversion
283   --  on return (the Out direction), the types must be reversed. This is
284   --  handled by the caller.
285
286   procedure Apply_Length_Check
287     (Ck_Node    : Node_Id;
288      Target_Typ : Entity_Id;
289      Source_Typ : Entity_Id := Empty);
290   --  This procedure builds a sequence of declarations to do a length check
291   --  that checks if the lengths of the two arrays Target_Typ and source type
292   --  are the same. The resulting actions are inserted at Node using a call
293   --  to Insert_Actions.
294   --
295   --  For access types, the Directly_Designated_Type is retrieved and
296   --  processing continues as enumerated above, with a guard against
297   --  null values.
298   --
299   --  Note: calls to Apply_Length_Check currently never supply an explicit
300   --  Source_Typ parameter, but Apply_Length_Check takes this parameter and
301   --  processes it as described above for consistency with the other routines
302   --  in this section.
303
304   procedure Apply_Range_Check
305     (Ck_Node    : Node_Id;
306      Target_Typ : Entity_Id;
307      Source_Typ : Entity_Id := Empty);
308   --  For an Node of kind N_Range, constructs a range check action that
309   --  tests first that the range is not null and then that the range
310   --  is contained in the Target_Typ range.
311   --
312   --  For scalar types, constructs a range check action that first tests that
313   --  the expression is contained in the Target_Typ range. The difference
314   --  between this and Apply_Scalar_Range_Check is that the latter generates
315   --  the actual checking code in gigi against the Etype of the expression.
316   --
317   --  For constrained array types, construct series of range check actions
318   --  to check that each Expr range is properly contained in the range of
319   --  Target_Typ.
320   --
321   --  For a type conversion to an unconstrained array type, constructs
322   --  a range check action to check that the bounds of the source type
323   --  are within the constraints imposed by the Target_Typ.
324   --
325   --  For access types, the Directly_Designated_Type is retrieved and
326   --  processing continues as enumerated above, with a guard against
327   --  null values.
328   --
329   --  The source type is used by type conversions to unconstrained array
330   --  types to retrieve the corresponding bounds.
331
332   procedure Apply_Static_Length_Check
333     (Expr       : Node_Id;
334      Target_Typ : Entity_Id;
335      Source_Typ : Entity_Id := Empty);
336   --  Tries to determine statically whether the two array types source type
337   --  and Target_Typ have the same length. If it can be determined at compile
338   --  time that they do not, then an N_Raise_Constraint_Error node replaces
339   --  Expr, and a warning message is issued.
340
341   procedure Apply_Scalar_Range_Check
342     (Expr       : Node_Id;
343      Target_Typ : Entity_Id;
344      Source_Typ : Entity_Id := Empty;
345      Fixed_Int  : Boolean   := False);
346   --  For scalar types, determines whether an expression node should be
347   --  flagged as needing a runtime range check. If the node requires such
348   --  a check, the Do_Range_Check flag is turned on. The Fixed_Int flag
349   --  if set causes any fixed-point values to be treated as though they
350   --  were discrete values (i.e. the underlying integer value is used).
351
352   type Check_Result is private;
353   --  Type used to return result of Range_Check call, for later use in
354   --  call to Insert_Range_Checks procedure.
355
356   procedure Append_Range_Checks
357     (Checks       : Check_Result;
358      Stmts        : List_Id;
359      Suppress_Typ : Entity_Id;
360      Static_Sloc  : Source_Ptr;
361      Flag_Node    : Node_Id);
362   --  Called to append range checks as returned by a call to Range_Check.
363   --  Stmts is a list to which either the dynamic check is appended or
364   --  the raise Constraint_Error statement is appended (for static checks).
365   --  Static_Sloc is the Sloc at which the raise CE node points,
366   --  Flag_Node is used as the node at which to set the Has_Dynamic_Check
367   --  flag. Checks_On is a boolean value that says if range and index checking
368   --  is on or not.
369
370   procedure Insert_Range_Checks
371     (Checks       : Check_Result;
372      Node         : Node_Id;
373      Suppress_Typ : Entity_Id;
374      Static_Sloc  : Source_Ptr := No_Location;
375      Flag_Node    : Node_Id    := Empty;
376      Do_Before    : Boolean    := False);
377   --  Called to insert range checks as returned by a call to Range_Check.
378   --  Node is the node after which either the dynamic check is inserted or
379   --  the raise Constraint_Error statement is inserted (for static checks).
380   --  Suppress_Typ is the type to check to determine if checks are suppressed.
381   --  Static_Sloc, if passed, is the Sloc at which the raise CE node points,
382   --  otherwise Sloc (Node) is used. The Has_Dynamic_Check flag is normally
383   --  set at Node. If Flag_Node is present, then this is used instead as the
384   --  node at which to set the Has_Dynamic_Check flag. Normally the check is
385   --  inserted after, if Do_Before is True, the check is inserted before
386   --  Node.
387
388   function Range_Check
389     (Ck_Node    : Node_Id;
390      Target_Typ : Entity_Id;
391      Source_Typ : Entity_Id := Empty;
392      Warn_Node  : Node_Id   := Empty)
393      return       Check_Result;
394   --  Like Apply_Range_Check, except it does not modify anything. Instead
395   --  it returns an encapsulated result of the check operations for later
396   --  use in a call to Insert_Range_Checks. If Warn_Node is non-empty, its
397   --  Sloc is used, in the static case, for the generated warning or error.
398   --  Additionally, it is used rather than Expr (or Low/High_Bound of Expr)
399   --  in constructing the check.
400
401   -----------------------
402   -- Expander Routines --
403   -----------------------
404
405   --  Some of the earlier processing for checks results in temporarily
406   --  setting the Do_Range_Check flag rather than actually generating
407   --  checks. Now we are moving the generation of such checks into the
408   --  front end for reasons of efficiency and simplicity (there were
409   --  difficutlies in handling this in the back end when side effects
410   --  were present in the expressions being checked).
411
412   --  Probably we could eliminate the Do_Range_Check flag entirely and
413   --  generate the checks earlier, but this is a delicate area and it
414   --  seemed safer to implement the following routines, which are called
415   --  late on in the expansion process. They check the Do_Range_Check flag
416   --  and if it is set, generate the actual checks and reset the flag.
417
418   procedure Generate_Range_Check
419     (N           : Node_Id;
420      Target_Type : Entity_Id;
421      Reason      : RT_Exception_Code);
422   --  This procedure is called to actually generate and insert a range
423   --  check. A check is generated to ensure that the value of N lies
424   --  within the range of the target type. Note that the base type of
425   --  N may be different from the base type of the target type. This
426   --  happens in the conversion case. The Reason parameter is the
427   --  exception code to be used for the exception if raised.
428   --
429   --  Note on the relation of this routine to the Do_Range_Check flag.
430   --  Mostly for historical reasons, we often set the Do_Range_Check
431   --  flag and then later we call Generate_Range_Check if this flag is
432   --  set. Most probably we could eliminate this intermediate setting
433   --  of the flag (historically the back end dealt with range checks,
434   --  using this flag to indicate if a check was required, then we
435   --  moved checks into the front end).
436
437   procedure Generate_Index_Checks (N : Node_Id);
438   --  This procedure is called to generate index checks on the subscripts
439   --  for the indexed component node N. Each subscript expression is
440   --  examined, and if the Do_Range_Check flag is set, an appropriate
441   --  index check is generated and the flag is reset.
442
443   --  Similarly, we set the flag Do_Discriminant_Check in the semantic
444   --  analysis to indicate that a discriminant check is required for a
445   --  selected component of a discriminated type. The following routine
446   --  is called from the expander to actually generate the call.
447
448   procedure Generate_Discriminant_Check (N : Node_Id);
449   --  N is a selected component for which a discriminant check is required
450   --  to make sure that the discriminants have appropriate values for the
451   --  selection. This is done by calling the appropriate discriminant
452   --  checking routine for the selector.
453
454   -----------------------
455   -- Validity Checking --
456   -----------------------
457
458   --  In (RM 13.9.1(9-11)) we have the following rules on invalid values
459
460   --    If the representation of a scalar object does not represent a
461   --    value of the object's subtype (perhaps because the object was not
462   --    initialized), the object is said to have an invalid representation.
463   --    It is a bounded error to evaluate the value of such an object.  If
464   --    the error is detected, either Constraint_Error or Program_Error is
465   --    raised.  Otherwise, execution continues using the invalid
466   --    representation.  The rules of the language outside this subclause
467   --    assume that all objects have valid representations.  The semantics
468   --    of operations on invalid representations are as follows:
469   --
470   --       10  If the representation of the object represents a value of the
471   --           object's type, the value of the type is used.
472   --
473   --       11  If the representation of the object does not represent a value
474   --           of the object's type, the semantics of operations on such
475   --           representations is implementation-defined, but does not by
476   --           itself lead to erroneous or unpredictable execution, or to
477   --           other objects becoming abnormal.
478
479   --  We quote the rules in full here since they are quite delicate. Most
480   --  of the time, we can just compute away with wrong values, and get a
481   --  possibly wrong result, which is well within the range of allowed
482   --  implementation defined behavior. The two tricky cases are subscripted
483   --  array assignments, where we don't want to do wild stores, and case
484   --  statements where we don't want to do wild jumps.
485
486   --  In GNAT, we control validity checking with a switch -gnatV that
487   --  can take three parameters, n/d/f for None/Default/Full. These
488   --  modes have the following meanings:
489
490   --    None (no validity checking)
491
492   --      In this mode, there is no specific checking for invalid values
493   --      and the code generator assumes that all stored values are always
494   --      within the bounds of the object subtype. The consequences are as
495   --      follows:
496
497   --        For case statements, an out of range invalid value will cause
498   --        Constraint_Error to be raised, or an arbitrary one of the case
499   --        alternatives will be executed. Wild jumps cannot result even
500   --        in this mode, since we always do a range check
501
502   --        For subscripted array assignments, wild stores will result in
503   --        the expected manner when addresses are calculated using values
504   --        of subscripts that are out of range.
505
506   --      It could perhaps be argued that this mode is still conformant with
507   --      the letter of the RM, since implementation defined is a rather
508   --      broad category, but certainly it is not in the spirit of the
509   --      RM requirement, since wild stores certainly seem to be a case of
510   --      erroneous behavior.
511
512   --    Default (default standard RM-compatible validity checking)
513
514   --      In this mode, which is the default, minimal validity checking is
515   --      performed to ensure no erroneous behavior as follows:
516
517   --        For case statements, an out of range invalid value will cause
518   --        Constraint_Error to be raised.
519
520   --        For subscripted array assignments, invalid out of range
521   --        subscript values will cause Constraint_Error to be raised.
522
523   --    Full (Full validity checking)
524
525   --      In this mode, the protections guaranteed by the standard mode are
526   --      in place, and the following additional checks are made:
527
528   --        For every assignment, the right side is checked for validity
529
530   --        For every call, IN and IN OUT parameters are checked for validity
531
532   --        For every subscripted array reference, both for stores and loads,
533   --        all subscripts are checked for validity.
534
535   --      These checks are not required by the RM, but will in practice
536   --      improve the detection of uninitialized variables, particularly
537   --      if used in conjunction with pragma Normalize_Scalars.
538
539   --  In the above description, we talk about performing validity checks,
540   --  but we don't actually generate a check in a case where the compiler
541   --  can be sure that the value is valid. Note that this assurance must
542   --  be achieved without assuming that any uninitialized value lies within
543   --  the range of its type. The following are cases in which values are
544   --  known to be valid. The flag Is_Known_Valid is used to keep track of
545   --  some of these cases.
546
547   --    If all possible stored values are valid, then any uninitialized
548   --    value must be valid.
549
550   --    Literals, including enumeration literals, are clearly always valid.
551
552   --    Constants are always assumed valid, with a validity check being
553   --    performed on the initializing value where necessary to ensure that
554   --    this is the case.
555
556   --    For variables, the status is set to known valid if there is an
557   --    initializing expression. Again a check is made on the initializing
558   --    value if necessary to ensure that this assumption is valid. The
559   --    status can change as a result of local assignments to a variable.
560   --    If a known valid value is unconditionally assigned, then we mark
561   --    the left side as known valid. If a value is assigned that is not
562   --    known to be valid, then we mark the left side as invalid. This
563   --    kind of processing does NOT apply to non-local variables since we
564   --    are not following the flow graph (more properly the flow of actual
565   --    processing only corresponds to the flow graph for local assignments).
566   --    For non-local variables, we preserve the current setting, i.e. a
567   --    validity check is performed when assigning to a knonwn valid global.
568
569   --  Note: no validity checking is required if range checks are suppressed
570   --  regardless of the setting of the validity checking mode.
571
572   --  The following procedures are used in handling validity checking
573
574   procedure Apply_Subscript_Validity_Checks (Expr : Node_Id);
575   --  Expr is the node for an indexed component. If validity checking and
576   --  range checking are enabled, all subscripts for this indexed component
577   --  are checked for validity.
578
579   procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id);
580   --  Expr is a lvalue, i.e. an expression representing the target of
581   --  an assignment. This procedure checks for this expression involving
582   --  an assignment to an array value. We have to be sure that all the
583   --  subscripts in such a case are valid, since according to the rules
584   --  in (RM 13.9.1(9-11)) such assignments are not permitted to result
585   --  in erroneous behavior in the case of invalid subscript values.
586
587   procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False);
588   --  Ensure that Expr represents a valid value of its type. If this type
589   --  is not a scalar type, then the call has no effect, since validity
590   --  is only an issue for scalar types. The effect of this call is to
591   --  check if the value is known valid, if so, nothing needs to be done.
592   --  If this is not known, then either Expr is set to be range checked,
593   --  or specific checking code is inserted so that an exception is raised
594   --  if the value is not valid.
595   --
596   --  The optional argument Holes_OK indicates whether it is necessary to
597   --  worry about enumeration types with non-standard representations leading
598   --  to "holes" in the range of possible representations. If Holes_OK is
599   --  True, then such values are assumed valid (this is used when the caller
600   --  will make a separate check for this case anyway). If Holes_OK is False,
601   --  then this case is checked, and code is inserted to ensure that Expr is
602   --  valid, raising Constraint_Error if the value is not valid.
603
604   function Expr_Known_Valid (Expr : Node_Id) return Boolean;
605   --  This function tests it the value of Expr is known to be valid in
606   --  the sense of RM 13.9.1(9-11). In the case of GNAT, it is only
607   --  discrete types which are a concern, since for non-discrete types
608   --  we simply continue computation with invalid values, which does
609   --  not lead to erroneous behavior. Thus Expr_Known_Valid always
610   --  returns True if the type of Expr is non-discrete. For discrete
611   --  types the value returned is True only if it can be determined
612   --  that the value is Valid. Otherwise False is returned.
613
614   procedure Insert_Valid_Check (Expr : Node_Id);
615   --  Inserts code that will check for the value of Expr being valid, in
616   --  the sense of the 'Valid attribute returning True. Constraint_Error
617   --  will be raised if the value is not valid.
618
619   procedure Remove_Checks (Expr : Node_Id);
620   --  Remove all checks from Expr except those that are only executed
621   --  conditionally (on the right side of And Then/Or Else. This call
622   --  removes only embedded checks (Do_Range_Check, Do_Overflow_Check).
623
624private
625
626   type Check_Result is array (Positive range 1 .. 2) of Node_Id;
627   --  There are two cases for the result returned by Range_Check:
628   --
629   --    For the static case the result is one or two nodes that should cause
630   --    a Constraint_Error. Typically these will include Expr itself or the
631   --    direct descendents of Expr, such as Low/High_Bound (Expr)). It is the
632   --    responsibility of the caller to rewrite and substitute the nodes with
633   --    N_Raise_Constraint_Error nodes.
634   --
635   --    For the non-static case a single N_Raise_Constraint_Error node
636   --    with a non-empty Condition field is returned.
637   --
638   --  Unused entries in Check_Result, if any, are simply set to Empty
639   --  For external clients, the required processing on this result is
640   --  achieved using the Insert_Range_Checks routine.
641
642   pragma Inline (Apply_Length_Check);
643   pragma Inline (Apply_Range_Check);
644   pragma Inline (Apply_Static_Length_Check);
645end Checks;
646