OSDN Git Service

2010-09-10 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.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-2010, 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 Debug;    use Debug;
28 with Einfo;    use Einfo;
29 with Errout;   use Errout;
30 with Exp_Ch2;  use Exp_Ch2;
31 with Exp_Ch4;  use Exp_Ch4;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Pakd; use Exp_Pakd;
34 with Exp_Util; use Exp_Util;
35 with Elists;   use Elists;
36 with Eval_Fat; use Eval_Fat;
37 with Freeze;   use Freeze;
38 with Lib;      use Lib;
39 with Nlists;   use Nlists;
40 with Nmake;    use Nmake;
41 with Opt;      use Opt;
42 with Output;   use Output;
43 with Restrict; use Restrict;
44 with Rident;   use Rident;
45 with Rtsfind;  use Rtsfind;
46 with Sem;      use Sem;
47 with Sem_Aux;  use Sem_Aux;
48 with Sem_Eval; use Sem_Eval;
49 with Sem_Ch3;  use Sem_Ch3;
50 with Sem_Ch8;  use Sem_Ch8;
51 with Sem_Res;  use Sem_Res;
52 with Sem_Util; use Sem_Util;
53 with Sem_Warn; use Sem_Warn;
54 with Sinfo;    use Sinfo;
55 with Sinput;   use Sinput;
56 with Snames;   use Snames;
57 with Sprint;   use Sprint;
58 with Stand;    use Stand;
59 with Targparm; use Targparm;
60 with Tbuild;   use Tbuild;
61 with Ttypes;   use Ttypes;
62 with Urealp;   use Urealp;
63 with Validsw;  use Validsw;
64
65 package body Checks is
66
67    --  General note: many of these routines are concerned with generating
68    --  checking code to make sure that constraint error is raised at runtime.
69    --  Clearly this code is only needed if the expander is active, since
70    --  otherwise we will not be generating code or going into the runtime
71    --  execution anyway.
72
73    --  We therefore disconnect most of these checks if the expander is
74    --  inactive. This has the additional benefit that we do not need to
75    --  worry about the tree being messed up by previous errors (since errors
76    --  turn off expansion anyway).
77
78    --  There are a few exceptions to the above rule. For instance routines
79    --  such as Apply_Scalar_Range_Check that do not insert any code can be
80    --  safely called even when the Expander is inactive (but Errors_Detected
81    --  is 0). The benefit of executing this code when expansion is off, is
82    --  the ability to emit constraint error warning for static expressions
83    --  even when we are not generating code.
84
85    -------------------------------------
86    -- Suppression of Redundant Checks --
87    -------------------------------------
88
89    --  This unit implements a limited circuit for removal of redundant
90    --  checks. The processing is based on a tracing of simple sequential
91    --  flow. For any sequence of statements, we save expressions that are
92    --  marked to be checked, and then if the same expression appears later
93    --  with the same check, then under certain circumstances, the second
94    --  check can be suppressed.
95
96    --  Basically, we can suppress the check if we know for certain that
97    --  the previous expression has been elaborated (together with its
98    --  check), and we know that the exception frame is the same, and that
99    --  nothing has happened to change the result of the exception.
100
101    --  Let us examine each of these three conditions in turn to describe
102    --  how we ensure that this condition is met.
103
104    --  First, we need to know for certain that the previous expression has
105    --  been executed. This is done principly by the mechanism of calling
106    --  Conditional_Statements_Begin at the start of any statement sequence
107    --  and Conditional_Statements_End at the end. The End call causes all
108    --  checks remembered since the Begin call to be discarded. This does
109    --  miss a few cases, notably the case of a nested BEGIN-END block with
110    --  no exception handlers. But the important thing is to be conservative.
111    --  The other protection is that all checks are discarded if a label
112    --  is encountered, since then the assumption of sequential execution
113    --  is violated, and we don't know enough about the flow.
114
115    --  Second, we need to know that the exception frame is the same. We
116    --  do this by killing all remembered checks when we enter a new frame.
117    --  Again, that's over-conservative, but generally the cases we can help
118    --  with are pretty local anyway (like the body of a loop for example).
119
120    --  Third, we must be sure to forget any checks which are no longer valid.
121    --  This is done by two mechanisms, first the Kill_Checks_Variable call is
122    --  used to note any changes to local variables. We only attempt to deal
123    --  with checks involving local variables, so we do not need to worry
124    --  about global variables. Second, a call to any non-global procedure
125    --  causes us to abandon all stored checks, since such a all may affect
126    --  the values of any local variables.
127
128    --  The following define the data structures used to deal with remembering
129    --  checks so that redundant checks can be eliminated as described above.
130
131    --  Right now, the only expressions that we deal with are of the form of
132    --  simple local objects (either declared locally, or IN parameters) or
133    --  such objects plus/minus a compile time known constant. We can do
134    --  more later on if it seems worthwhile, but this catches many simple
135    --  cases in practice.
136
137    --  The following record type reflects a single saved check. An entry
138    --  is made in the stack of saved checks if and only if the expression
139    --  has been elaborated with the indicated checks.
140
141    type Saved_Check is record
142       Killed : Boolean;
143       --  Set True if entry is killed by Kill_Checks
144
145       Entity : Entity_Id;
146       --  The entity involved in the expression that is checked
147
148       Offset : Uint;
149       --  A compile time value indicating the result of adding or
150       --  subtracting a compile time value. This value is to be
151       --  added to the value of the Entity. A value of zero is
152       --  used for the case of a simple entity reference.
153
154       Check_Type : Character;
155       --  This is set to 'R' for a range check (in which case Target_Type
156       --  is set to the target type for the range check) or to 'O' for an
157       --  overflow check (in which case Target_Type is set to Empty).
158
159       Target_Type : Entity_Id;
160       --  Used only if Do_Range_Check is set. Records the target type for
161       --  the check. We need this, because a check is a duplicate only if
162       --  it has a the same target type (or more accurately one with a
163       --  range that is smaller or equal to the stored target type of a
164       --  saved check).
165    end record;
166
167    --  The following table keeps track of saved checks. Rather than use an
168    --  extensible table. We just use a table of fixed size, and we discard
169    --  any saved checks that do not fit. That's very unlikely to happen and
170    --  this is only an optimization in any case.
171
172    Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
173    --  Array of saved checks
174
175    Num_Saved_Checks : Nat := 0;
176    --  Number of saved checks
177
178    --  The following stack keeps track of statement ranges. It is treated
179    --  as a stack. When Conditional_Statements_Begin is called, an entry
180    --  is pushed onto this stack containing the value of Num_Saved_Checks
181    --  at the time of the call. Then when Conditional_Statements_End is
182    --  called, this value is popped off and used to reset Num_Saved_Checks.
183
184    --  Note: again, this is a fixed length stack with a size that should
185    --  always be fine. If the value of the stack pointer goes above the
186    --  limit, then we just forget all saved checks.
187
188    Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
189    Saved_Checks_TOS : Nat := 0;
190
191    -----------------------
192    -- Local Subprograms --
193    -----------------------
194
195    procedure Apply_Float_Conversion_Check
196      (Ck_Node    : Node_Id;
197       Target_Typ : Entity_Id);
198    --  The checks on a conversion from a floating-point type to an integer
199    --  type are delicate. They have to be performed before conversion, they
200    --  have to raise an exception when the operand is a NaN, and rounding must
201    --  be taken into account to determine the safe bounds of the operand.
202
203    procedure Apply_Selected_Length_Checks
204      (Ck_Node    : Node_Id;
205       Target_Typ : Entity_Id;
206       Source_Typ : Entity_Id;
207       Do_Static  : Boolean);
208    --  This is the subprogram that does all the work for Apply_Length_Check
209    --  and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
210    --  described for the above routines. The Do_Static flag indicates that
211    --  only a static check is to be done.
212
213    procedure Apply_Selected_Range_Checks
214      (Ck_Node    : Node_Id;
215       Target_Typ : Entity_Id;
216       Source_Typ : Entity_Id;
217       Do_Static  : Boolean);
218    --  This is the subprogram that does all the work for Apply_Range_Check.
219    --  Expr, Target_Typ and Source_Typ are as described for the above
220    --  routine. The Do_Static flag indicates that only a static check is
221    --  to be done.
222
223    type Check_Type is new Check_Id range Access_Check .. Division_Check;
224    function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
225    --  This function is used to see if an access or division by zero check is
226    --  needed. The check is to be applied to a single variable appearing in the
227    --  source, and N is the node for the reference. If N is not of this form,
228    --  True is returned with no further processing. If N is of the right form,
229    --  then further processing determines if the given Check is needed.
230    --
231    --  The particular circuit is to see if we have the case of a check that is
232    --  not needed because it appears in the right operand of a short circuited
233    --  conditional where the left operand guards the check. For example:
234    --
235    --    if Var = 0 or else Q / Var > 12 then
236    --       ...
237    --    end if;
238    --
239    --  In this example, the division check is not required. At the same time
240    --  we can issue warnings for suspicious use of non-short-circuited forms,
241    --  such as:
242    --
243    --    if Var = 0 or Q / Var > 12 then
244    --       ...
245    --    end if;
246
247    procedure Find_Check
248      (Expr        : Node_Id;
249       Check_Type  : Character;
250       Target_Type : Entity_Id;
251       Entry_OK    : out Boolean;
252       Check_Num   : out Nat;
253       Ent         : out Entity_Id;
254       Ofs         : out Uint);
255    --  This routine is used by Enable_Range_Check and Enable_Overflow_Check
256    --  to see if a check is of the form for optimization, and if so, to see
257    --  if it has already been performed. Expr is the expression to check,
258    --  and Check_Type is 'R' for a range check, 'O' for an overflow check.
259    --  Target_Type is the target type for a range check, and Empty for an
260    --  overflow check. If the entry is not of the form for optimization,
261    --  then Entry_OK is set to False, and the remaining out parameters
262    --  are undefined. If the entry is OK, then Ent/Ofs are set to the
263    --  entity and offset from the expression. Check_Num is the number of
264    --  a matching saved entry in Saved_Checks, or zero if no such entry
265    --  is located.
266
267    function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
268    --  If a discriminal is used in constraining a prival, Return reference
269    --  to the discriminal of the protected body (which renames the parameter
270    --  of the enclosing protected operation). This clumsy transformation is
271    --  needed because privals are created too late and their actual subtypes
272    --  are not available when analysing the bodies of the protected operations.
273    --  This function is called whenever the bound is an entity and the scope
274    --  indicates a protected operation. If the bound is an in-parameter of
275    --  a protected operation that is not a prival, the function returns the
276    --  bound itself.
277    --  To be cleaned up???
278
279    function Guard_Access
280      (Cond    : Node_Id;
281       Loc     : Source_Ptr;
282       Ck_Node : Node_Id) return Node_Id;
283    --  In the access type case, guard the test with a test to ensure
284    --  that the access value is non-null, since the checks do not
285    --  not apply to null access values.
286
287    procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
288    --  Called by Apply_{Length,Range}_Checks to rewrite the tree with the
289    --  Constraint_Error node.
290
291    function Range_Or_Validity_Checks_Suppressed
292      (Expr : Node_Id) return Boolean;
293    --  Returns True if either range or validity checks or both are suppressed
294    --  for the type of the given expression, or, if the expression is the name
295    --  of an entity, if these checks are suppressed for the entity.
296
297    function Selected_Length_Checks
298      (Ck_Node    : Node_Id;
299       Target_Typ : Entity_Id;
300       Source_Typ : Entity_Id;
301       Warn_Node  : Node_Id) return Check_Result;
302    --  Like Apply_Selected_Length_Checks, except it doesn't modify
303    --  anything, just returns a list of nodes as described in the spec of
304    --  this package for the Range_Check function.
305
306    function Selected_Range_Checks
307      (Ck_Node    : Node_Id;
308       Target_Typ : Entity_Id;
309       Source_Typ : Entity_Id;
310       Warn_Node  : Node_Id) return Check_Result;
311    --  Like Apply_Selected_Range_Checks, except it doesn't modify anything,
312    --  just returns a list of nodes as described in the spec of this package
313    --  for the Range_Check function.
314
315    ------------------------------
316    -- Access_Checks_Suppressed --
317    ------------------------------
318
319    function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
320    begin
321       if Present (E) and then Checks_May_Be_Suppressed (E) then
322          return Is_Check_Suppressed (E, Access_Check);
323       else
324          return Scope_Suppress (Access_Check);
325       end if;
326    end Access_Checks_Suppressed;
327
328    -------------------------------------
329    -- Accessibility_Checks_Suppressed --
330    -------------------------------------
331
332    function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
333    begin
334       if Present (E) and then Checks_May_Be_Suppressed (E) then
335          return Is_Check_Suppressed (E, Accessibility_Check);
336       else
337          return Scope_Suppress (Accessibility_Check);
338       end if;
339    end Accessibility_Checks_Suppressed;
340
341    -----------------------------
342    -- Activate_Division_Check --
343    -----------------------------
344
345    procedure Activate_Division_Check (N : Node_Id) is
346    begin
347       Set_Do_Division_Check (N, True);
348       Possible_Local_Raise (N, Standard_Constraint_Error);
349    end Activate_Division_Check;
350
351    -----------------------------
352    -- Activate_Overflow_Check --
353    -----------------------------
354
355    procedure Activate_Overflow_Check (N : Node_Id) is
356    begin
357       Set_Do_Overflow_Check (N, True);
358       Possible_Local_Raise (N, Standard_Constraint_Error);
359    end Activate_Overflow_Check;
360
361    --------------------------
362    -- Activate_Range_Check --
363    --------------------------
364
365    procedure Activate_Range_Check (N : Node_Id) is
366    begin
367       Set_Do_Range_Check (N, True);
368       Possible_Local_Raise (N, Standard_Constraint_Error);
369    end Activate_Range_Check;
370
371    ---------------------------------
372    -- Alignment_Checks_Suppressed --
373    ---------------------------------
374
375    function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
376    begin
377       if Present (E) and then Checks_May_Be_Suppressed (E) then
378          return Is_Check_Suppressed (E, Alignment_Check);
379       else
380          return Scope_Suppress (Alignment_Check);
381       end if;
382    end Alignment_Checks_Suppressed;
383
384    -------------------------
385    -- Append_Range_Checks --
386    -------------------------
387
388    procedure Append_Range_Checks
389      (Checks       : Check_Result;
390       Stmts        : List_Id;
391       Suppress_Typ : Entity_Id;
392       Static_Sloc  : Source_Ptr;
393       Flag_Node    : Node_Id)
394    is
395       Internal_Flag_Node   : constant Node_Id    := Flag_Node;
396       Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
397
398       Checks_On : constant Boolean :=
399                     (not Index_Checks_Suppressed (Suppress_Typ))
400                        or else
401                     (not Range_Checks_Suppressed (Suppress_Typ));
402
403    begin
404       --  For now we just return if Checks_On is false, however this should
405       --  be enhanced to check for an always True value in the condition
406       --  and to generate a compilation warning???
407
408       if not Checks_On then
409          return;
410       end if;
411
412       for J in 1 .. 2 loop
413          exit when No (Checks (J));
414
415          if Nkind (Checks (J)) = N_Raise_Constraint_Error
416            and then Present (Condition (Checks (J)))
417          then
418             if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
419                Append_To (Stmts, Checks (J));
420                Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
421             end if;
422
423          else
424             Append_To
425               (Stmts,
426                 Make_Raise_Constraint_Error (Internal_Static_Sloc,
427                   Reason => CE_Range_Check_Failed));
428          end if;
429       end loop;
430    end Append_Range_Checks;
431
432    ------------------------
433    -- Apply_Access_Check --
434    ------------------------
435
436    procedure Apply_Access_Check (N : Node_Id) is
437       P : constant Node_Id := Prefix (N);
438
439    begin
440       --  We do not need checks if we are not generating code (i.e. the
441       --  expander is not active). This is not just an optimization, there
442       --  are cases (e.g. with pragma Debug) where generating the checks
443       --  can cause real trouble).
444
445       if not Expander_Active then
446          return;
447       end if;
448
449       --  No check if short circuiting makes check unnecessary
450
451       if not Check_Needed (P, Access_Check) then
452          return;
453       end if;
454
455       --  No check if accessing the Offset_To_Top component of a dispatch
456       --  table. They are safe by construction.
457
458       if Tagged_Type_Expansion
459         and then Present (Etype (P))
460         and then RTU_Loaded (Ada_Tags)
461         and then RTE_Available (RE_Offset_To_Top_Ptr)
462         and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
463       then
464          return;
465       end if;
466
467       --  Otherwise go ahead and install the check
468
469       Install_Null_Excluding_Check (P);
470    end Apply_Access_Check;
471
472    -------------------------------
473    -- Apply_Accessibility_Check --
474    -------------------------------
475
476    procedure Apply_Accessibility_Check
477      (N           : Node_Id;
478       Typ         : Entity_Id;
479       Insert_Node : Node_Id)
480    is
481       Loc         : constant Source_Ptr := Sloc (N);
482       Param_Ent   : constant Entity_Id  := Param_Entity (N);
483       Param_Level : Node_Id;
484       Type_Level  : Node_Id;
485
486    begin
487       if Inside_A_Generic then
488          return;
489
490       --  Only apply the run-time check if the access parameter has an
491       --  associated extra access level parameter and when the level of the
492       --  type is less deep than the level of the access parameter, and
493       --  accessibility checks are not suppressed.
494
495       elsif Present (Param_Ent)
496          and then Present (Extra_Accessibility (Param_Ent))
497          and then UI_Gt (Object_Access_Level (N), Type_Access_Level (Typ))
498          and then not Accessibility_Checks_Suppressed (Param_Ent)
499          and then not Accessibility_Checks_Suppressed (Typ)
500       then
501          Param_Level :=
502            New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
503
504          Type_Level :=
505            Make_Integer_Literal (Loc, Type_Access_Level (Typ));
506
507          --  Raise Program_Error if the accessibility level of the access
508          --  parameter is deeper than the level of the target access type.
509
510          Insert_Action (Insert_Node,
511            Make_Raise_Program_Error (Loc,
512              Condition =>
513                Make_Op_Gt (Loc,
514                  Left_Opnd  => Param_Level,
515                  Right_Opnd => Type_Level),
516              Reason => PE_Accessibility_Check_Failed));
517
518          Analyze_And_Resolve (N);
519       end if;
520    end Apply_Accessibility_Check;
521
522    --------------------------------
523    -- Apply_Address_Clause_Check --
524    --------------------------------
525
526    procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
527       AC   : constant Node_Id    := Address_Clause (E);
528       Loc  : constant Source_Ptr := Sloc (AC);
529       Typ  : constant Entity_Id  := Etype (E);
530       Aexp : constant Node_Id    := Expression (AC);
531
532       Expr : Node_Id;
533       --  Address expression (not necessarily the same as Aexp, for example
534       --  when Aexp is a reference to a constant, in which case Expr gets
535       --  reset to reference the value expression of the constant.
536
537       procedure Compile_Time_Bad_Alignment;
538       --  Post error warnings when alignment is known to be incompatible. Note
539       --  that we do not go as far as inserting a raise of Program_Error since
540       --  this is an erroneous case, and it may happen that we are lucky and an
541       --  underaligned address turns out to be OK after all.
542
543       --------------------------------
544       -- Compile_Time_Bad_Alignment --
545       --------------------------------
546
547       procedure Compile_Time_Bad_Alignment is
548       begin
549          if Address_Clause_Overlay_Warnings then
550             Error_Msg_FE
551               ("?specified address for& may be inconsistent with alignment ",
552                Aexp, E);
553             Error_Msg_FE
554               ("\?program execution may be erroneous (RM 13.3(27))",
555                Aexp, E);
556             Set_Address_Warning_Posted (AC);
557          end if;
558       end Compile_Time_Bad_Alignment;
559
560    --  Start of processing for Apply_Address_Clause_Check
561
562    begin
563       --  See if alignment check needed. Note that we never need a check if the
564       --  maximum alignment is one, since the check will always succeed.
565
566       --  Note: we do not check for checks suppressed here, since that check
567       --  was done in Sem_Ch13 when the address clause was processed. We are
568       --  only called if checks were not suppressed. The reason for this is
569       --  that we have to delay the call to Apply_Alignment_Check till freeze
570       --  time (so that all types etc are elaborated), but we have to check
571       --  the status of check suppressing at the point of the address clause.
572
573       if No (AC)
574         or else not Check_Address_Alignment (AC)
575         or else Maximum_Alignment = 1
576       then
577          return;
578       end if;
579
580       --  Obtain expression from address clause
581
582       Expr := Expression (AC);
583
584       --  The following loop digs for the real expression to use in the check
585
586       loop
587          --  For constant, get constant expression
588
589          if Is_Entity_Name (Expr)
590            and then Ekind (Entity (Expr)) = E_Constant
591          then
592             Expr := Constant_Value (Entity (Expr));
593
594          --  For unchecked conversion, get result to convert
595
596          elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
597             Expr := Expression (Expr);
598
599          --  For (common case) of To_Address call, get argument
600
601          elsif Nkind (Expr) = N_Function_Call
602            and then Is_Entity_Name (Name (Expr))
603            and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
604          then
605             Expr := First (Parameter_Associations (Expr));
606
607             if Nkind (Expr) = N_Parameter_Association then
608                Expr := Explicit_Actual_Parameter (Expr);
609             end if;
610
611          --  We finally have the real expression
612
613          else
614             exit;
615          end if;
616       end loop;
617
618       --  See if we know that Expr has a bad alignment at compile time
619
620       if Compile_Time_Known_Value (Expr)
621         and then (Known_Alignment (E) or else Known_Alignment (Typ))
622       then
623          declare
624             AL : Uint := Alignment (Typ);
625
626          begin
627             --  The object alignment might be more restrictive than the
628             --  type alignment.
629
630             if Known_Alignment (E) then
631                AL := Alignment (E);
632             end if;
633
634             if Expr_Value (Expr) mod AL /= 0 then
635                Compile_Time_Bad_Alignment;
636             else
637                return;
638             end if;
639          end;
640
641       --  If the expression has the form X'Address, then we can find out if
642       --  the object X has an alignment that is compatible with the object E.
643       --  If it hasn't or we don't know, we defer issuing the warning until
644       --  the end of the compilation to take into account back end annotations.
645
646       elsif Nkind (Expr) = N_Attribute_Reference
647         and then Attribute_Name (Expr) = Name_Address
648         and then Has_Compatible_Alignment (E, Prefix (Expr)) = Known_Compatible
649       then
650          return;
651       end if;
652
653       --  Here we do not know if the value is acceptable. Stricly we don't have
654       --  to do anything, since if the alignment is bad, we have an erroneous
655       --  program. However we are allowed to check for erroneous conditions and
656       --  we decide to do this by default if the check is not suppressed.
657
658       --  However, don't do the check if elaboration code is unwanted
659
660       if Restriction_Active (No_Elaboration_Code) then
661          return;
662
663       --  Generate a check to raise PE if alignment may be inappropriate
664
665       else
666          --  If the original expression is a non-static constant, use the
667          --  name of the constant itself rather than duplicating its
668          --  defining expression, which was extracted above.
669
670          --  Note: Expr is empty if the address-clause is applied to in-mode
671          --  actuals (allowed by 13.1(22)).
672
673          if not Present (Expr)
674            or else
675              (Is_Entity_Name (Expression (AC))
676                and then Ekind (Entity (Expression (AC))) = E_Constant
677                and then Nkind (Parent (Entity (Expression (AC))))
678                                  = N_Object_Declaration)
679          then
680             Expr := New_Copy_Tree (Expression (AC));
681          else
682             Remove_Side_Effects (Expr);
683          end if;
684
685          Insert_After_And_Analyze (N,
686            Make_Raise_Program_Error (Loc,
687              Condition =>
688                Make_Op_Ne (Loc,
689                  Left_Opnd =>
690                    Make_Op_Mod (Loc,
691                      Left_Opnd =>
692                        Unchecked_Convert_To
693                          (RTE (RE_Integer_Address), Expr),
694                      Right_Opnd =>
695                        Make_Attribute_Reference (Loc,
696                          Prefix => New_Occurrence_Of (E, Loc),
697                          Attribute_Name => Name_Alignment)),
698                  Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
699              Reason => PE_Misaligned_Address_Value),
700            Suppress => All_Checks);
701          return;
702       end if;
703
704    exception
705       --  If we have some missing run time component in configurable run time
706       --  mode then just skip the check (it is not required in any case).
707
708       when RE_Not_Available =>
709          return;
710    end Apply_Address_Clause_Check;
711
712    -------------------------------------
713    -- Apply_Arithmetic_Overflow_Check --
714    -------------------------------------
715
716    --  This routine is called only if the type is an integer type, and a
717    --  software arithmetic overflow check may be needed for op (add, subtract,
718    --  or multiply). This check is performed only if Software_Overflow_Checking
719    --  is enabled and Do_Overflow_Check is set. In this case we expand the
720    --  operation into a more complex sequence of tests that ensures that
721    --  overflow is properly caught.
722
723    procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
724       Loc   : constant Source_Ptr := Sloc (N);
725       Typ   : constant Entity_Id  := Etype (N);
726       Rtyp  : constant Entity_Id  := Root_Type (Typ);
727
728    begin
729       --  An interesting special case. If the arithmetic operation appears as
730       --  the operand of a type conversion:
731
732       --    type1 (x op y)
733
734       --  and all the following conditions apply:
735
736       --    arithmetic operation is for a signed integer type
737       --    target type type1 is a static integer subtype
738       --    range of x and y are both included in the range of type1
739       --    range of x op y is included in the range of type1
740       --    size of type1 is at least twice the result size of op
741
742       --  then we don't do an overflow check in any case, instead we transform
743       --  the operation so that we end up with:
744
745       --    type1 (type1 (x) op type1 (y))
746
747       --  This avoids intermediate overflow before the conversion. It is
748       --  explicitly permitted by RM 3.5.4(24):
749
750       --    For the execution of a predefined operation of a signed integer
751       --    type, the implementation need not raise Constraint_Error if the
752       --    result is outside the base range of the type, so long as the
753       --    correct result is produced.
754
755       --  It's hard to imagine that any programmer counts on the exception
756       --  being raised in this case, and in any case it's wrong coding to
757       --  have this expectation, given the RM permission. Furthermore, other
758       --  Ada compilers do allow such out of range results.
759
760       --  Note that we do this transformation even if overflow checking is
761       --  off, since this is precisely about giving the "right" result and
762       --  avoiding the need for an overflow check.
763
764       --  Note: this circuit is partially redundant with respect to the similar
765       --  processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
766       --  with cases that do not come through here. We still need the following
767       --  processing even with the Exp_Ch4 code in place, since we want to be
768       --  sure not to generate the arithmetic overflow check in these cases
769       --  (Exp_Ch4 would have a hard time removing them once generated).
770
771       if Is_Signed_Integer_Type (Typ)
772         and then Nkind (Parent (N)) = N_Type_Conversion
773       then
774          declare
775             Target_Type : constant Entity_Id :=
776                             Base_Type (Entity (Subtype_Mark (Parent (N))));
777
778             Llo, Lhi : Uint;
779             Rlo, Rhi : Uint;
780             LOK, ROK : Boolean;
781
782             Vlo : Uint;
783             Vhi : Uint;
784             VOK : Boolean;
785
786             Tlo : Uint;
787             Thi : Uint;
788
789          begin
790             if Is_Integer_Type (Target_Type)
791               and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
792             then
793                Tlo := Expr_Value (Type_Low_Bound  (Target_Type));
794                Thi := Expr_Value (Type_High_Bound (Target_Type));
795
796                Determine_Range
797                  (Left_Opnd  (N), LOK, Llo, Lhi, Assume_Valid => True);
798                Determine_Range
799                  (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
800
801                if (LOK and ROK)
802                  and then Tlo <= Llo and then Lhi <= Thi
803                  and then Tlo <= Rlo and then Rhi <= Thi
804                then
805                   Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
806
807                   if VOK and then Tlo <= Vlo and then Vhi <= Thi then
808                      Rewrite (Left_Opnd (N),
809                        Make_Type_Conversion (Loc,
810                          Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
811                          Expression   => Relocate_Node (Left_Opnd (N))));
812
813                      Rewrite (Right_Opnd (N),
814                        Make_Type_Conversion (Loc,
815                         Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
816                         Expression   => Relocate_Node (Right_Opnd (N))));
817
818                      --  Rewrite the conversion operand so that the original
819                      --  node is retained, in order to avoid the warning for
820                      --  redundant conversions in Resolve_Type_Conversion.
821
822                      --  The above comment is uncomfortable. This seems like
823                      --  an awkward covert channel, since there isno general
824                      --  requirement in sinfo.ads or einfo.ads that requires
825                      --  this rewrite. Instead, the issue seems to be that in
826                      --  the old code, some node was incorrectly marked as
827                      --  coming from source when it should not have been and/or
828                      --  the warning code did not properly test the appropriate
829                      --  Comes_From_Soure flag. ???
830
831                      Rewrite (N, Relocate_Node (N));
832
833                      Set_Etype (N, Target_Type);
834
835                      Analyze_And_Resolve (Left_Opnd  (N), Target_Type);
836                      Analyze_And_Resolve (Right_Opnd (N), Target_Type);
837
838                      --  Given that the target type is twice the size of the
839                      --  source type, overflow is now impossible, so we can
840                      --  safely kill the overflow check and return.
841
842                      Set_Do_Overflow_Check (N, False);
843                      return;
844                   end if;
845                end if;
846             end if;
847          end;
848       end if;
849
850       --  Now see if an overflow check is required
851
852       declare
853          Siz   : constant Int := UI_To_Int (Esize (Rtyp));
854          Dsiz  : constant Int := Siz * 2;
855          Opnod : Node_Id;
856          Ctyp  : Entity_Id;
857          Opnd  : Node_Id;
858          Cent  : RE_Id;
859
860       begin
861          --  Skip check if back end does overflow checks, or the overflow flag
862          --  is not set anyway, or we are not doing code expansion, or the
863          --  parent node is a type conversion whose operand is an arithmetic
864          --  operation on signed integers on which the expander can promote
865          --  later the operands to type Integer (see Expand_N_Type_Conversion).
866
867          --  Special case CLI target, where arithmetic overflow checks can be
868          --  performed for integer and long_integer
869
870          if Backend_Overflow_Checks_On_Target
871            or else not Do_Overflow_Check (N)
872            or else not Expander_Active
873            or else (Present (Parent (N))
874                      and then Nkind (Parent (N)) = N_Type_Conversion
875                      and then Integer_Promotion_Possible (Parent (N)))
876            or else
877              (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
878          then
879             return;
880          end if;
881
882          --  Otherwise, generate the full general code for front end overflow
883          --  detection, which works by doing arithmetic in a larger type:
884
885          --    x op y
886
887          --  is expanded into
888
889          --    Typ (Checktyp (x) op Checktyp (y));
890
891          --  where Typ is the type of the original expression, and Checktyp is
892          --  an integer type of sufficient length to hold the largest possible
893          --  result.
894
895          --  If the size of check type exceeds the size of Long_Long_Integer,
896          --  we use a different approach, expanding to:
897
898          --    typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
899
900          --  where xxx is Add, Multiply or Subtract as appropriate
901
902          --  Find check type if one exists
903
904          if Dsiz <= Standard_Integer_Size then
905             Ctyp := Standard_Integer;
906
907          elsif Dsiz <= Standard_Long_Long_Integer_Size then
908             Ctyp := Standard_Long_Long_Integer;
909
910             --  No check type exists, use runtime call
911
912          else
913             if Nkind (N) = N_Op_Add then
914                Cent := RE_Add_With_Ovflo_Check;
915
916             elsif Nkind (N) = N_Op_Multiply then
917                Cent := RE_Multiply_With_Ovflo_Check;
918
919             else
920                pragma Assert (Nkind (N) = N_Op_Subtract);
921                Cent := RE_Subtract_With_Ovflo_Check;
922             end if;
923
924             Rewrite (N,
925               OK_Convert_To (Typ,
926                 Make_Function_Call (Loc,
927                   Name => New_Reference_To (RTE (Cent), Loc),
928                   Parameter_Associations => New_List (
929                     OK_Convert_To (RTE (RE_Integer_64), Left_Opnd  (N)),
930                     OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
931
932             Analyze_And_Resolve (N, Typ);
933             return;
934          end if;
935
936          --  If we fall through, we have the case where we do the arithmetic
937          --  in the next higher type and get the check by conversion. In these
938          --  cases Ctyp is set to the type to be used as the check type.
939
940          Opnod := Relocate_Node (N);
941
942          Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
943
944          Analyze (Opnd);
945          Set_Etype (Opnd, Ctyp);
946          Set_Analyzed (Opnd, True);
947          Set_Left_Opnd (Opnod, Opnd);
948
949          Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
950
951          Analyze (Opnd);
952          Set_Etype (Opnd, Ctyp);
953          Set_Analyzed (Opnd, True);
954          Set_Right_Opnd (Opnod, Opnd);
955
956          --  The type of the operation changes to the base type of the check
957          --  type, and we reset the overflow check indication, since clearly no
958          --  overflow is possible now that we are using a double length type.
959          --  We also set the Analyzed flag to avoid a recursive attempt to
960          --  expand the node.
961
962          Set_Etype             (Opnod, Base_Type (Ctyp));
963          Set_Do_Overflow_Check (Opnod, False);
964          Set_Analyzed          (Opnod, True);
965
966          --  Now build the outer conversion
967
968          Opnd := OK_Convert_To (Typ, Opnod);
969          Analyze (Opnd);
970          Set_Etype (Opnd, Typ);
971
972          --  In the discrete type case, we directly generate the range check
973          --  for the outer operand. This range check will implement the
974          --  required overflow check.
975
976          if Is_Discrete_Type (Typ) then
977             Rewrite (N, Opnd);
978             Generate_Range_Check
979               (Expression (N), Typ, CE_Overflow_Check_Failed);
980
981          --  For other types, we enable overflow checking on the conversion,
982          --  after setting the node as analyzed to prevent recursive attempts
983          --  to expand the conversion node.
984
985          else
986             Set_Analyzed (Opnd, True);
987             Enable_Overflow_Check (Opnd);
988             Rewrite (N, Opnd);
989          end if;
990
991       exception
992          when RE_Not_Available =>
993             return;
994       end;
995    end Apply_Arithmetic_Overflow_Check;
996
997    ----------------------------
998    -- Apply_Constraint_Check --
999    ----------------------------
1000
1001    procedure Apply_Constraint_Check
1002      (N          : Node_Id;
1003       Typ        : Entity_Id;
1004       No_Sliding : Boolean := False)
1005    is
1006       Desig_Typ : Entity_Id;
1007
1008    begin
1009       if Inside_A_Generic then
1010          return;
1011
1012       elsif Is_Scalar_Type (Typ) then
1013          Apply_Scalar_Range_Check (N, Typ);
1014
1015       elsif Is_Array_Type (Typ) then
1016
1017          --  A useful optimization: an aggregate with only an others clause
1018          --  always has the right bounds.
1019
1020          if Nkind (N) = N_Aggregate
1021            and then No (Expressions (N))
1022            and then Nkind
1023             (First (Choices (First (Component_Associations (N)))))
1024               = N_Others_Choice
1025          then
1026             return;
1027          end if;
1028
1029          if Is_Constrained (Typ) then
1030             Apply_Length_Check (N, Typ);
1031
1032             if No_Sliding then
1033                Apply_Range_Check (N, Typ);
1034             end if;
1035          else
1036             Apply_Range_Check (N, Typ);
1037          end if;
1038
1039       elsif (Is_Record_Type (Typ)
1040                or else Is_Private_Type (Typ))
1041         and then Has_Discriminants (Base_Type (Typ))
1042         and then Is_Constrained (Typ)
1043       then
1044          Apply_Discriminant_Check (N, Typ);
1045
1046       elsif Is_Access_Type (Typ) then
1047
1048          Desig_Typ := Designated_Type (Typ);
1049
1050          --  No checks necessary if expression statically null
1051
1052          if Known_Null (N) then
1053             if Can_Never_Be_Null (Typ) then
1054                Install_Null_Excluding_Check (N);
1055             end if;
1056
1057          --  No sliding possible on access to arrays
1058
1059          elsif Is_Array_Type (Desig_Typ) then
1060             if Is_Constrained (Desig_Typ) then
1061                Apply_Length_Check (N, Typ);
1062             end if;
1063
1064             Apply_Range_Check (N, Typ);
1065
1066          elsif Has_Discriminants (Base_Type (Desig_Typ))
1067             and then Is_Constrained (Desig_Typ)
1068          then
1069             Apply_Discriminant_Check (N, Typ);
1070          end if;
1071
1072          --  Apply the 2005 Null_Excluding check. Note that we do not apply
1073          --  this check if the constraint node is illegal, as shown by having
1074          --  an error posted. This additional guard prevents cascaded errors
1075          --  and compiler aborts on illegal programs involving Ada 2005 checks.
1076
1077          if Can_Never_Be_Null (Typ)
1078            and then not Can_Never_Be_Null (Etype (N))
1079            and then not Error_Posted (N)
1080          then
1081             Install_Null_Excluding_Check (N);
1082          end if;
1083       end if;
1084    end Apply_Constraint_Check;
1085
1086    ------------------------------
1087    -- Apply_Discriminant_Check --
1088    ------------------------------
1089
1090    procedure Apply_Discriminant_Check
1091      (N   : Node_Id;
1092       Typ : Entity_Id;
1093       Lhs : Node_Id := Empty)
1094    is
1095       Loc       : constant Source_Ptr := Sloc (N);
1096       Do_Access : constant Boolean    := Is_Access_Type (Typ);
1097       S_Typ     : Entity_Id  := Etype (N);
1098       Cond      : Node_Id;
1099       T_Typ     : Entity_Id;
1100
1101       function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1102       --  A heap object with an indefinite subtype is constrained by its
1103       --  initial value, and assigning to it requires a constraint_check.
1104       --  The target may be an explicit dereference, or a renaming of one.
1105
1106       function Is_Aliased_Unconstrained_Component return Boolean;
1107       --  It is possible for an aliased component to have a nominal
1108       --  unconstrained subtype (through instantiation). If this is a
1109       --  discriminated component assigned in the expansion of an aggregate
1110       --  in an initialization, the check must be suppressed. This unusual
1111       --  situation requires a predicate of its own.
1112
1113       ----------------------------------
1114       -- Denotes_Explicit_Dereference --
1115       ----------------------------------
1116
1117       function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1118       begin
1119          return
1120            Nkind (Obj) = N_Explicit_Dereference
1121              or else
1122                (Is_Entity_Name (Obj)
1123                  and then Present (Renamed_Object (Entity (Obj)))
1124                  and then Nkind (Renamed_Object (Entity (Obj))) =
1125                                               N_Explicit_Dereference);
1126       end Denotes_Explicit_Dereference;
1127
1128       ----------------------------------------
1129       -- Is_Aliased_Unconstrained_Component --
1130       ----------------------------------------
1131
1132       function Is_Aliased_Unconstrained_Component return Boolean is
1133          Comp : Entity_Id;
1134          Pref : Node_Id;
1135
1136       begin
1137          if Nkind (Lhs) /= N_Selected_Component then
1138             return False;
1139          else
1140             Comp := Entity (Selector_Name (Lhs));
1141             Pref := Prefix (Lhs);
1142          end if;
1143
1144          if Ekind (Comp) /= E_Component
1145            or else not Is_Aliased (Comp)
1146          then
1147             return False;
1148          end if;
1149
1150          return not Comes_From_Source (Pref)
1151            and then In_Instance
1152            and then not Is_Constrained (Etype (Comp));
1153       end Is_Aliased_Unconstrained_Component;
1154
1155    --  Start of processing for Apply_Discriminant_Check
1156
1157    begin
1158       if Do_Access then
1159          T_Typ := Designated_Type (Typ);
1160       else
1161          T_Typ := Typ;
1162       end if;
1163
1164       --  Nothing to do if discriminant checks are suppressed or else no code
1165       --  is to be generated
1166
1167       if not Expander_Active
1168         or else Discriminant_Checks_Suppressed (T_Typ)
1169       then
1170          return;
1171       end if;
1172
1173       --  No discriminant checks necessary for an access when expression is
1174       --  statically Null. This is not only an optimization, it is fundamental
1175       --  because otherwise discriminant checks may be generated in init procs
1176       --  for types containing an access to a not-yet-frozen record, causing a
1177       --  deadly forward reference.
1178
1179       --  Also, if the expression is of an access type whose designated type is
1180       --  incomplete, then the access value must be null and we suppress the
1181       --  check.
1182
1183       if Known_Null (N) then
1184          return;
1185
1186       elsif Is_Access_Type (S_Typ) then
1187          S_Typ := Designated_Type (S_Typ);
1188
1189          if Ekind (S_Typ) = E_Incomplete_Type then
1190             return;
1191          end if;
1192       end if;
1193
1194       --  If an assignment target is present, then we need to generate the
1195       --  actual subtype if the target is a parameter or aliased object with
1196       --  an unconstrained nominal subtype.
1197
1198       --  Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1199       --  subtype to the parameter and dereference cases, since other aliased
1200       --  objects are unconstrained (unless the nominal subtype is explicitly
1201       --  constrained).
1202
1203       if Present (Lhs)
1204         and then (Present (Param_Entity (Lhs))
1205                    or else (Ada_Version < Ada_05
1206                              and then not Is_Constrained (T_Typ)
1207                              and then Is_Aliased_View (Lhs)
1208                              and then not Is_Aliased_Unconstrained_Component)
1209                    or else (Ada_Version >= Ada_05
1210                              and then not Is_Constrained (T_Typ)
1211                              and then Denotes_Explicit_Dereference (Lhs)
1212                              and then Nkind (Original_Node (Lhs)) /=
1213                                         N_Function_Call))
1214       then
1215          T_Typ := Get_Actual_Subtype (Lhs);
1216       end if;
1217
1218       --  Nothing to do if the type is unconstrained (this is the case where
1219       --  the actual subtype in the RM sense of N is unconstrained and no check
1220       --  is required).
1221
1222       if not Is_Constrained (T_Typ) then
1223          return;
1224
1225       --  Ada 2005: nothing to do if the type is one for which there is a
1226       --  partial view that is constrained.
1227
1228       elsif Ada_Version >= Ada_05
1229         and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1230       then
1231          return;
1232       end if;
1233
1234       --  Nothing to do if the type is an Unchecked_Union
1235
1236       if Is_Unchecked_Union (Base_Type (T_Typ)) then
1237          return;
1238       end if;
1239
1240       --  Suppress checks if the subtypes are the same. the check must be
1241       --  preserved in an assignment to a formal, because the constraint is
1242       --  given by the actual.
1243
1244       if Nkind (Original_Node (N)) /= N_Allocator
1245         and then (No (Lhs)
1246           or else not Is_Entity_Name (Lhs)
1247           or else No (Param_Entity (Lhs)))
1248       then
1249          if (Etype (N) = Typ
1250               or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1251            and then not Is_Aliased_View (Lhs)
1252          then
1253             return;
1254          end if;
1255
1256       --  We can also eliminate checks on allocators with a subtype mark that
1257       --  coincides with the context type. The context type may be a subtype
1258       --  without a constraint (common case, a generic actual).
1259
1260       elsif Nkind (Original_Node (N)) = N_Allocator
1261         and then Is_Entity_Name (Expression (Original_Node (N)))
1262       then
1263          declare
1264             Alloc_Typ : constant Entity_Id :=
1265                           Entity (Expression (Original_Node (N)));
1266
1267          begin
1268             if Alloc_Typ = T_Typ
1269               or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1270                         and then Is_Entity_Name (
1271                           Subtype_Indication (Parent (T_Typ)))
1272                         and then Alloc_Typ = Base_Type (T_Typ))
1273
1274             then
1275                return;
1276             end if;
1277          end;
1278       end if;
1279
1280       --  See if we have a case where the types are both constrained, and all
1281       --  the constraints are constants. In this case, we can do the check
1282       --  successfully at compile time.
1283
1284       --  We skip this check for the case where the node is a rewritten`
1285       --  allocator, because it already carries the context subtype, and
1286       --  extracting the discriminants from the aggregate is messy.
1287
1288       if Is_Constrained (S_Typ)
1289         and then Nkind (Original_Node (N)) /= N_Allocator
1290       then
1291          declare
1292             DconT : Elmt_Id;
1293             Discr : Entity_Id;
1294             DconS : Elmt_Id;
1295             ItemS : Node_Id;
1296             ItemT : Node_Id;
1297
1298          begin
1299             --  S_Typ may not have discriminants in the case where it is a
1300             --  private type completed by a default discriminated type. In that
1301             --  case, we need to get the constraints from the underlying_type.
1302             --  If the underlying type is unconstrained (i.e. has no default
1303             --  discriminants) no check is needed.
1304
1305             if Has_Discriminants (S_Typ) then
1306                Discr := First_Discriminant (S_Typ);
1307                DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1308
1309             else
1310                Discr := First_Discriminant (Underlying_Type (S_Typ));
1311                DconS :=
1312                  First_Elmt
1313                    (Discriminant_Constraint (Underlying_Type (S_Typ)));
1314
1315                if No (DconS) then
1316                   return;
1317                end if;
1318
1319                --  A further optimization: if T_Typ is derived from S_Typ
1320                --  without imposing a constraint, no check is needed.
1321
1322                if Nkind (Original_Node (Parent (T_Typ))) =
1323                  N_Full_Type_Declaration
1324                then
1325                   declare
1326                      Type_Def : constant Node_Id :=
1327                                  Type_Definition
1328                                    (Original_Node (Parent (T_Typ)));
1329                   begin
1330                      if Nkind (Type_Def) = N_Derived_Type_Definition
1331                        and then Is_Entity_Name (Subtype_Indication (Type_Def))
1332                        and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1333                      then
1334                         return;
1335                      end if;
1336                   end;
1337                end if;
1338             end if;
1339
1340             DconT  := First_Elmt (Discriminant_Constraint (T_Typ));
1341
1342             while Present (Discr) loop
1343                ItemS := Node (DconS);
1344                ItemT := Node (DconT);
1345
1346                --  For a discriminated component type constrained by the
1347                --  current instance of an enclosing type, there is no
1348                --  applicable discriminant check.
1349
1350                if Nkind (ItemT) = N_Attribute_Reference
1351                  and then Is_Access_Type (Etype (ItemT))
1352                  and then Is_Entity_Name (Prefix (ItemT))
1353                  and then Is_Type (Entity (Prefix (ItemT)))
1354                then
1355                   return;
1356                end if;
1357
1358                --  If the expressions for the discriminants are identical
1359                --  and it is side-effect free (for now just an entity),
1360                --  this may be a shared constraint, e.g. from a subtype
1361                --  without a constraint introduced as a generic actual.
1362                --  Examine other discriminants if any.
1363
1364                if ItemS = ItemT
1365                  and then Is_Entity_Name (ItemS)
1366                then
1367                   null;
1368
1369                elsif not Is_OK_Static_Expression (ItemS)
1370                  or else not Is_OK_Static_Expression (ItemT)
1371                then
1372                   exit;
1373
1374                elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1375                   if Do_Access then   --  needs run-time check.
1376                      exit;
1377                   else
1378                      Apply_Compile_Time_Constraint_Error
1379                        (N, "incorrect value for discriminant&?",
1380                         CE_Discriminant_Check_Failed, Ent => Discr);
1381                      return;
1382                   end if;
1383                end if;
1384
1385                Next_Elmt (DconS);
1386                Next_Elmt (DconT);
1387                Next_Discriminant (Discr);
1388             end loop;
1389
1390             if No (Discr) then
1391                return;
1392             end if;
1393          end;
1394       end if;
1395
1396       --  Here we need a discriminant check. First build the expression
1397       --  for the comparisons of the discriminants:
1398
1399       --    (n.disc1 /= typ.disc1) or else
1400       --    (n.disc2 /= typ.disc2) or else
1401       --     ...
1402       --    (n.discn /= typ.discn)
1403
1404       Cond := Build_Discriminant_Checks (N, T_Typ);
1405
1406       --  If Lhs is set and is a parameter, then the condition is
1407       --  guarded by: lhs'constrained and then (condition built above)
1408
1409       if Present (Param_Entity (Lhs)) then
1410          Cond :=
1411            Make_And_Then (Loc,
1412              Left_Opnd =>
1413                Make_Attribute_Reference (Loc,
1414                  Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1415                  Attribute_Name => Name_Constrained),
1416              Right_Opnd => Cond);
1417       end if;
1418
1419       if Do_Access then
1420          Cond := Guard_Access (Cond, Loc, N);
1421       end if;
1422
1423       Insert_Action (N,
1424         Make_Raise_Constraint_Error (Loc,
1425           Condition => Cond,
1426           Reason    => CE_Discriminant_Check_Failed));
1427    end Apply_Discriminant_Check;
1428
1429    ------------------------
1430    -- Apply_Divide_Check --
1431    ------------------------
1432
1433    procedure Apply_Divide_Check (N : Node_Id) is
1434       Loc   : constant Source_Ptr := Sloc (N);
1435       Typ   : constant Entity_Id  := Etype (N);
1436       Left  : constant Node_Id    := Left_Opnd (N);
1437       Right : constant Node_Id    := Right_Opnd (N);
1438
1439       LLB : Uint;
1440       Llo : Uint;
1441       Lhi : Uint;
1442       LOK : Boolean;
1443       Rlo : Uint;
1444       Rhi : Uint;
1445       ROK   : Boolean;
1446
1447       pragma Warnings (Off, Lhi);
1448       --  Don't actually use this value
1449
1450    begin
1451       if Expander_Active
1452         and then not Backend_Divide_Checks_On_Target
1453         and then Check_Needed (Right, Division_Check)
1454       then
1455          Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1456
1457          --  See if division by zero possible, and if so generate test. This
1458          --  part of the test is not controlled by the -gnato switch.
1459
1460          if Do_Division_Check (N) then
1461             if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1462                Insert_Action (N,
1463                  Make_Raise_Constraint_Error (Loc,
1464                    Condition =>
1465                      Make_Op_Eq (Loc,
1466                        Left_Opnd  => Duplicate_Subexpr_Move_Checks (Right),
1467                        Right_Opnd => Make_Integer_Literal (Loc, 0)),
1468                    Reason => CE_Divide_By_Zero));
1469             end if;
1470          end if;
1471
1472          --  Test for extremely annoying case of xxx'First divided by -1
1473
1474          if Do_Overflow_Check (N) then
1475             if Nkind (N) = N_Op_Divide
1476               and then Is_Signed_Integer_Type (Typ)
1477             then
1478                Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1479                LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1480
1481                if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1482                  and then
1483                  ((not LOK) or else (Llo = LLB))
1484                then
1485                   Insert_Action (N,
1486                     Make_Raise_Constraint_Error (Loc,
1487                       Condition =>
1488                         Make_And_Then (Loc,
1489
1490                            Make_Op_Eq (Loc,
1491                              Left_Opnd  =>
1492                                Duplicate_Subexpr_Move_Checks (Left),
1493                              Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1494
1495                            Make_Op_Eq (Loc,
1496                              Left_Opnd =>
1497                                Duplicate_Subexpr (Right),
1498                              Right_Opnd =>
1499                                Make_Integer_Literal (Loc, -1))),
1500                       Reason => CE_Overflow_Check_Failed));
1501                end if;
1502             end if;
1503          end if;
1504       end if;
1505    end Apply_Divide_Check;
1506
1507    ----------------------------------
1508    -- Apply_Float_Conversion_Check --
1509    ----------------------------------
1510
1511    --  Let F and I be the source and target types of the conversion. The RM
1512    --  specifies that a floating-point value X is rounded to the nearest
1513    --  integer, with halfway cases being rounded away from zero. The rounded
1514    --  value of X is checked against I'Range.
1515
1516    --  The catch in the above paragraph is that there is no good way to know
1517    --  whether the round-to-integer operation resulted in overflow. A remedy is
1518    --  to perform a range check in the floating-point domain instead, however:
1519
1520    --      (1)  The bounds may not be known at compile time
1521    --      (2)  The check must take into account rounding or truncation.
1522    --      (3)  The range of type I may not be exactly representable in F.
1523    --      (4)  For the rounding case, The end-points I'First - 0.5 and
1524    --           I'Last + 0.5 may or may not be in range, depending on the
1525    --           sign of  I'First and I'Last.
1526    --      (5)  X may be a NaN, which will fail any comparison
1527
1528    --  The following steps correctly convert X with rounding:
1529
1530    --      (1) If either I'First or I'Last is not known at compile time, use
1531    --          I'Base instead of I in the next three steps and perform a
1532    --          regular range check against I'Range after conversion.
1533    --      (2) If I'First - 0.5 is representable in F then let Lo be that
1534    --          value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1535    --          F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1536    --          In other words, take one of the closest floating-point numbers
1537    --          (which is an integer value) to I'First, and see if it is in
1538    --          range or not.
1539    --      (3) If I'Last + 0.5 is representable in F then let Hi be that value
1540    --          and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1541    --          F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1542    --      (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1543    --                     or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1544
1545    --  For the truncating case, replace steps (2) and (3) as follows:
1546    --      (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1547    --          be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1548    --          Lo_OK be True.
1549    --      (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1550    --          be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1551    --          Hi_OK be False
1552
1553    procedure Apply_Float_Conversion_Check
1554      (Ck_Node    : Node_Id;
1555       Target_Typ : Entity_Id)
1556    is
1557       LB          : constant Node_Id    := Type_Low_Bound (Target_Typ);
1558       HB          : constant Node_Id    := Type_High_Bound (Target_Typ);
1559       Loc         : constant Source_Ptr := Sloc (Ck_Node);
1560       Expr_Type   : constant Entity_Id  := Base_Type (Etype (Ck_Node));
1561       Target_Base : constant Entity_Id  :=
1562                       Implementation_Base_Type (Target_Typ);
1563
1564       Par : constant Node_Id := Parent (Ck_Node);
1565       pragma Assert (Nkind (Par) = N_Type_Conversion);
1566       --  Parent of check node, must be a type conversion
1567
1568       Truncate  : constant Boolean := Float_Truncate (Par);
1569       Max_Bound : constant Uint :=
1570                     UI_Expon
1571                       (Machine_Radix (Expr_Type),
1572                        Machine_Mantissa (Expr_Type) - 1) - 1;
1573
1574       --  Largest bound, so bound plus or minus half is a machine number of F
1575
1576       Ifirst, Ilast : Uint;
1577       --  Bounds of integer type
1578
1579       Lo, Hi : Ureal;
1580       --  Bounds to check in floating-point domain
1581
1582       Lo_OK, Hi_OK : Boolean;
1583       --  True iff Lo resp. Hi belongs to I'Range
1584
1585       Lo_Chk, Hi_Chk : Node_Id;
1586       --  Expressions that are False iff check fails
1587
1588       Reason : RT_Exception_Code;
1589
1590    begin
1591       if not Compile_Time_Known_Value (LB)
1592           or not Compile_Time_Known_Value (HB)
1593       then
1594          declare
1595             --  First check that the value falls in the range of the base type,
1596             --  to prevent overflow during conversion and then perform a
1597             --  regular range check against the (dynamic) bounds.
1598
1599             pragma Assert (Target_Base /= Target_Typ);
1600
1601             Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
1602
1603          begin
1604             Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1605             Set_Etype (Temp, Target_Base);
1606
1607             Insert_Action (Parent (Par),
1608               Make_Object_Declaration (Loc,
1609                 Defining_Identifier => Temp,
1610                 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1611                 Expression => New_Copy_Tree (Par)),
1612                 Suppress => All_Checks);
1613
1614             Insert_Action (Par,
1615               Make_Raise_Constraint_Error (Loc,
1616                 Condition =>
1617                   Make_Not_In (Loc,
1618                     Left_Opnd  => New_Occurrence_Of (Temp, Loc),
1619                     Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1620                 Reason => CE_Range_Check_Failed));
1621             Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1622
1623             return;
1624          end;
1625       end if;
1626
1627       --  Get the (static) bounds of the target type
1628
1629       Ifirst := Expr_Value (LB);
1630       Ilast  := Expr_Value (HB);
1631
1632       --  A simple optimization: if the expression is a universal literal,
1633       --  we can do the comparison with the bounds and the conversion to
1634       --  an integer type statically. The range checks are unchanged.
1635
1636       if Nkind (Ck_Node) = N_Real_Literal
1637         and then Etype (Ck_Node) = Universal_Real
1638         and then Is_Integer_Type (Target_Typ)
1639         and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
1640       then
1641          declare
1642             Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
1643
1644          begin
1645             if Int_Val <= Ilast and then Int_Val >= Ifirst then
1646
1647                --  Conversion is safe
1648
1649                Rewrite (Parent (Ck_Node),
1650                  Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
1651                Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
1652                return;
1653             end if;
1654          end;
1655       end if;
1656
1657       --  Check against lower bound
1658
1659       if Truncate and then Ifirst > 0 then
1660          Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1661          Lo_OK := False;
1662
1663       elsif Truncate then
1664          Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1665          Lo_OK := True;
1666
1667       elsif abs (Ifirst) < Max_Bound then
1668          Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1669          Lo_OK := (Ifirst > 0);
1670
1671       else
1672          Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1673          Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1674       end if;
1675
1676       if Lo_OK then
1677
1678          --  Lo_Chk := (X >= Lo)
1679
1680          Lo_Chk := Make_Op_Ge (Loc,
1681                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1682                      Right_Opnd => Make_Real_Literal (Loc, Lo));
1683
1684       else
1685          --  Lo_Chk := (X > Lo)
1686
1687          Lo_Chk := Make_Op_Gt (Loc,
1688                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1689                      Right_Opnd => Make_Real_Literal (Loc, Lo));
1690       end if;
1691
1692       --  Check against higher bound
1693
1694       if Truncate and then Ilast < 0 then
1695          Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1696          Lo_OK := False;
1697
1698       elsif Truncate then
1699          Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1700          Hi_OK := True;
1701
1702       elsif abs (Ilast) < Max_Bound then
1703          Hi := UR_From_Uint (Ilast) + Ureal_Half;
1704          Hi_OK := (Ilast < 0);
1705       else
1706          Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1707          Hi_OK := (Hi <= UR_From_Uint (Ilast));
1708       end if;
1709
1710       if Hi_OK then
1711
1712          --  Hi_Chk := (X <= Hi)
1713
1714          Hi_Chk := Make_Op_Le (Loc,
1715                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1716                      Right_Opnd => Make_Real_Literal (Loc, Hi));
1717
1718       else
1719          --  Hi_Chk := (X < Hi)
1720
1721          Hi_Chk := Make_Op_Lt (Loc,
1722                      Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1723                      Right_Opnd => Make_Real_Literal (Loc, Hi));
1724       end if;
1725
1726       --  If the bounds of the target type are the same as those of the base
1727       --  type, the check is an overflow check as a range check is not
1728       --  performed in these cases.
1729
1730       if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1731         and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1732       then
1733          Reason := CE_Overflow_Check_Failed;
1734       else
1735          Reason := CE_Range_Check_Failed;
1736       end if;
1737
1738       --  Raise CE if either conditions does not hold
1739
1740       Insert_Action (Ck_Node,
1741         Make_Raise_Constraint_Error (Loc,
1742           Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1743           Reason    => Reason));
1744    end Apply_Float_Conversion_Check;
1745
1746    ------------------------
1747    -- Apply_Length_Check --
1748    ------------------------
1749
1750    procedure Apply_Length_Check
1751      (Ck_Node    : Node_Id;
1752       Target_Typ : Entity_Id;
1753       Source_Typ : Entity_Id := Empty)
1754    is
1755    begin
1756       Apply_Selected_Length_Checks
1757         (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1758    end Apply_Length_Check;
1759
1760    -----------------------
1761    -- Apply_Range_Check --
1762    -----------------------
1763
1764    procedure Apply_Range_Check
1765      (Ck_Node    : Node_Id;
1766       Target_Typ : Entity_Id;
1767       Source_Typ : Entity_Id := Empty)
1768    is
1769    begin
1770       Apply_Selected_Range_Checks
1771         (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1772    end Apply_Range_Check;
1773
1774    ------------------------------
1775    -- Apply_Scalar_Range_Check --
1776    ------------------------------
1777
1778    --  Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1779    --  off if it is already set on.
1780
1781    procedure Apply_Scalar_Range_Check
1782      (Expr       : Node_Id;
1783       Target_Typ : Entity_Id;
1784       Source_Typ : Entity_Id := Empty;
1785       Fixed_Int  : Boolean   := False)
1786    is
1787       Parnt   : constant Node_Id := Parent (Expr);
1788       S_Typ   : Entity_Id;
1789       Arr     : Node_Id   := Empty;  -- initialize to prevent warning
1790       Arr_Typ : Entity_Id := Empty;  -- initialize to prevent warning
1791       OK      : Boolean;
1792
1793       Is_Subscr_Ref : Boolean;
1794       --  Set true if Expr is a subscript
1795
1796       Is_Unconstrained_Subscr_Ref : Boolean;
1797       --  Set true if Expr is a subscript of an unconstrained array. In this
1798       --  case we do not attempt to do an analysis of the value against the
1799       --  range of the subscript, since we don't know the actual subtype.
1800
1801       Int_Real : Boolean;
1802       --  Set to True if Expr should be regarded as a real value even though
1803       --  the type of Expr might be discrete.
1804
1805       procedure Bad_Value;
1806       --  Procedure called if value is determined to be out of range
1807
1808       ---------------
1809       -- Bad_Value --
1810       ---------------
1811
1812       procedure Bad_Value is
1813       begin
1814          Apply_Compile_Time_Constraint_Error
1815            (Expr, "value not in range of}?", CE_Range_Check_Failed,
1816             Ent => Target_Typ,
1817             Typ => Target_Typ);
1818       end Bad_Value;
1819
1820    --  Start of processing for Apply_Scalar_Range_Check
1821
1822    begin
1823       --  Return if check obviously not needed
1824
1825       if
1826          --  Not needed inside generic
1827
1828          Inside_A_Generic
1829
1830          --  Not needed if previous error
1831
1832          or else Target_Typ = Any_Type
1833          or else Nkind (Expr) = N_Error
1834
1835          --  Not needed for non-scalar type
1836
1837          or else not Is_Scalar_Type (Target_Typ)
1838
1839          --  Not needed if we know node raises CE already
1840
1841          or else Raises_Constraint_Error (Expr)
1842       then
1843          return;
1844       end if;
1845
1846       --  Now, see if checks are suppressed
1847
1848       Is_Subscr_Ref :=
1849         Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1850
1851       if Is_Subscr_Ref then
1852          Arr := Prefix (Parnt);
1853          Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1854       end if;
1855
1856       if not Do_Range_Check (Expr) then
1857
1858          --  Subscript reference. Check for Index_Checks suppressed
1859
1860          if Is_Subscr_Ref then
1861
1862             --  Check array type and its base type
1863
1864             if Index_Checks_Suppressed (Arr_Typ)
1865               or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1866             then
1867                return;
1868
1869             --  Check array itself if it is an entity name
1870
1871             elsif Is_Entity_Name (Arr)
1872               and then Index_Checks_Suppressed (Entity (Arr))
1873             then
1874                return;
1875
1876             --  Check expression itself if it is an entity name
1877
1878             elsif Is_Entity_Name (Expr)
1879               and then Index_Checks_Suppressed (Entity (Expr))
1880             then
1881                return;
1882             end if;
1883
1884          --  All other cases, check for Range_Checks suppressed
1885
1886          else
1887             --  Check target type and its base type
1888
1889             if Range_Checks_Suppressed (Target_Typ)
1890               or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1891             then
1892                return;
1893
1894             --  Check expression itself if it is an entity name
1895
1896             elsif Is_Entity_Name (Expr)
1897               and then Range_Checks_Suppressed (Entity (Expr))
1898             then
1899                return;
1900
1901             --  If Expr is part of an assignment statement, then check left
1902             --  side of assignment if it is an entity name.
1903
1904             elsif Nkind (Parnt) = N_Assignment_Statement
1905               and then Is_Entity_Name (Name (Parnt))
1906               and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1907             then
1908                return;
1909             end if;
1910          end if;
1911       end if;
1912
1913       --  Do not set range checks if they are killed
1914
1915       if Nkind (Expr) = N_Unchecked_Type_Conversion
1916         and then Kill_Range_Check (Expr)
1917       then
1918          return;
1919       end if;
1920
1921       --  Do not set range checks for any values from System.Scalar_Values
1922       --  since the whole idea of such values is to avoid checking them!
1923
1924       if Is_Entity_Name (Expr)
1925         and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1926       then
1927          return;
1928       end if;
1929
1930       --  Now see if we need a check
1931
1932       if No (Source_Typ) then
1933          S_Typ := Etype (Expr);
1934       else
1935          S_Typ := Source_Typ;
1936       end if;
1937
1938       if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1939          return;
1940       end if;
1941
1942       Is_Unconstrained_Subscr_Ref :=
1943         Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1944
1945       --  Always do a range check if the source type includes infinities and
1946       --  the target type does not include infinities. We do not do this if
1947       --  range checks are killed.
1948
1949       if Is_Floating_Point_Type (S_Typ)
1950         and then Has_Infinities (S_Typ)
1951         and then not Has_Infinities (Target_Typ)
1952       then
1953          Enable_Range_Check (Expr);
1954       end if;
1955
1956       --  Return if we know expression is definitely in the range of the target
1957       --  type as determined by Determine_Range. Right now we only do this for
1958       --  discrete types, and not fixed-point or floating-point types.
1959
1960       --  The additional less-precise tests below catch these cases
1961
1962       --  Note: skip this if we are given a source_typ, since the point of
1963       --  supplying a Source_Typ is to stop us looking at the expression.
1964       --  We could sharpen this test to be out parameters only ???
1965
1966       if Is_Discrete_Type (Target_Typ)
1967         and then Is_Discrete_Type (Etype (Expr))
1968         and then not Is_Unconstrained_Subscr_Ref
1969         and then No (Source_Typ)
1970       then
1971          declare
1972             Tlo : constant Node_Id := Type_Low_Bound  (Target_Typ);
1973             Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1974             Lo  : Uint;
1975             Hi  : Uint;
1976
1977          begin
1978             if Compile_Time_Known_Value (Tlo)
1979               and then Compile_Time_Known_Value (Thi)
1980             then
1981                declare
1982                   Lov : constant Uint := Expr_Value (Tlo);
1983                   Hiv : constant Uint := Expr_Value (Thi);
1984
1985                begin
1986                   --  If range is null, we for sure have a constraint error
1987                   --  (we don't even need to look at the value involved,
1988                   --  since all possible values will raise CE).
1989
1990                   if Lov > Hiv then
1991                      Bad_Value;
1992                      return;
1993                   end if;
1994
1995                   --  Otherwise determine range of value
1996
1997                   Determine_Range (Expr, OK, Lo, Hi, Assume_Valid => True);
1998
1999                   if OK then
2000
2001                      --  If definitely in range, all OK
2002
2003                      if Lo >= Lov and then Hi <= Hiv then
2004                         return;
2005
2006                      --  If definitely not in range, warn
2007
2008                      elsif Lov > Hi or else Hiv < Lo then
2009                         Bad_Value;
2010                         return;
2011
2012                      --  Otherwise we don't know
2013
2014                      else
2015                         null;
2016                      end if;
2017                   end if;
2018                end;
2019             end if;
2020          end;
2021       end if;
2022
2023       Int_Real :=
2024         Is_Floating_Point_Type (S_Typ)
2025           or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
2026
2027       --  Check if we can determine at compile time whether Expr is in the
2028       --  range of the target type. Note that if S_Typ is within the bounds
2029       --  of Target_Typ then this must be the case. This check is meaningful
2030       --  only if this is not a conversion between integer and real types.
2031
2032       if not Is_Unconstrained_Subscr_Ref
2033         and then
2034            Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
2035         and then
2036           (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
2037              or else
2038                Is_In_Range (Expr, Target_Typ,
2039                             Assume_Valid => True,
2040                             Fixed_Int => Fixed_Int,
2041                             Int_Real  => Int_Real))
2042       then
2043          return;
2044
2045       elsif Is_Out_Of_Range (Expr, Target_Typ,
2046                              Assume_Valid => True,
2047                              Fixed_Int    => Fixed_Int,
2048                              Int_Real     => Int_Real)
2049       then
2050          Bad_Value;
2051          return;
2052
2053       --  In the floating-point case, we only do range checks if the type is
2054       --  constrained. We definitely do NOT want range checks for unconstrained
2055       --  types, since we want to have infinities
2056
2057       elsif Is_Floating_Point_Type (S_Typ) then
2058          if Is_Constrained (S_Typ) then
2059             Enable_Range_Check (Expr);
2060          end if;
2061
2062       --  For all other cases we enable a range check unconditionally
2063
2064       else
2065          Enable_Range_Check (Expr);
2066          return;
2067       end if;
2068    end Apply_Scalar_Range_Check;
2069
2070    ----------------------------------
2071    -- Apply_Selected_Length_Checks --
2072    ----------------------------------
2073
2074    procedure Apply_Selected_Length_Checks
2075      (Ck_Node    : Node_Id;
2076       Target_Typ : Entity_Id;
2077       Source_Typ : Entity_Id;
2078       Do_Static  : Boolean)
2079    is
2080       Cond     : Node_Id;
2081       R_Result : Check_Result;
2082       R_Cno    : Node_Id;
2083
2084       Loc         : constant Source_Ptr := Sloc (Ck_Node);
2085       Checks_On   : constant Boolean :=
2086                       (not Index_Checks_Suppressed (Target_Typ))
2087                         or else
2088                       (not Length_Checks_Suppressed (Target_Typ));
2089
2090    begin
2091       if not Expander_Active then
2092          return;
2093       end if;
2094
2095       R_Result :=
2096         Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2097
2098       for J in 1 .. 2 loop
2099          R_Cno := R_Result (J);
2100          exit when No (R_Cno);
2101
2102          --  A length check may mention an Itype which is attached to a
2103          --  subsequent node. At the top level in a package this can cause
2104          --  an order-of-elaboration problem, so we make sure that the itype
2105          --  is referenced now.
2106
2107          if Ekind (Current_Scope) = E_Package
2108            and then Is_Compilation_Unit (Current_Scope)
2109          then
2110             Ensure_Defined (Target_Typ, Ck_Node);
2111
2112             if Present (Source_Typ) then
2113                Ensure_Defined (Source_Typ, Ck_Node);
2114
2115             elsif Is_Itype (Etype (Ck_Node)) then
2116                Ensure_Defined (Etype (Ck_Node), Ck_Node);
2117             end if;
2118          end if;
2119
2120          --  If the item is a conditional raise of constraint error, then have
2121          --  a look at what check is being performed and ???
2122
2123          if Nkind (R_Cno) = N_Raise_Constraint_Error
2124            and then Present (Condition (R_Cno))
2125          then
2126             Cond := Condition (R_Cno);
2127
2128             --  Case where node does not now have a dynamic check
2129
2130             if not Has_Dynamic_Length_Check (Ck_Node) then
2131
2132                --  If checks are on, just insert the check
2133
2134                if Checks_On then
2135                   Insert_Action (Ck_Node, R_Cno);
2136
2137                   if not Do_Static then
2138                      Set_Has_Dynamic_Length_Check (Ck_Node);
2139                   end if;
2140
2141                --  If checks are off, then analyze the length check after
2142                --  temporarily attaching it to the tree in case the relevant
2143                --  condition can be evaluted at compile time. We still want a
2144                --  compile time warning in this case.
2145
2146                else
2147                   Set_Parent (R_Cno, Ck_Node);
2148                   Analyze (R_Cno);
2149                end if;
2150             end if;
2151
2152             --  Output a warning if the condition is known to be True
2153
2154             if Is_Entity_Name (Cond)
2155               and then Entity (Cond) = Standard_True
2156             then
2157                Apply_Compile_Time_Constraint_Error
2158                  (Ck_Node, "wrong length for array of}?",
2159                   CE_Length_Check_Failed,
2160                   Ent => Target_Typ,
2161                   Typ => Target_Typ);
2162
2163             --  If we were only doing a static check, or if checks are not
2164             --  on, then we want to delete the check, since it is not needed.
2165             --  We do this by replacing the if statement by a null statement
2166
2167             elsif Do_Static or else not Checks_On then
2168                Remove_Warning_Messages (R_Cno);
2169                Rewrite (R_Cno, Make_Null_Statement (Loc));
2170             end if;
2171
2172          else
2173             Install_Static_Check (R_Cno, Loc);
2174          end if;
2175       end loop;
2176    end Apply_Selected_Length_Checks;
2177
2178    ---------------------------------
2179    -- Apply_Selected_Range_Checks --
2180    ---------------------------------
2181
2182    procedure Apply_Selected_Range_Checks
2183      (Ck_Node    : Node_Id;
2184       Target_Typ : Entity_Id;
2185       Source_Typ : Entity_Id;
2186       Do_Static  : Boolean)
2187    is
2188       Cond     : Node_Id;
2189       R_Result : Check_Result;
2190       R_Cno    : Node_Id;
2191
2192       Loc       : constant Source_Ptr := Sloc (Ck_Node);
2193       Checks_On : constant Boolean :=
2194                     (not Index_Checks_Suppressed (Target_Typ))
2195                       or else
2196                     (not Range_Checks_Suppressed (Target_Typ));
2197
2198    begin
2199       if not Expander_Active or else not Checks_On then
2200          return;
2201       end if;
2202
2203       R_Result :=
2204         Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2205
2206       for J in 1 .. 2 loop
2207
2208          R_Cno := R_Result (J);
2209          exit when No (R_Cno);
2210
2211          --  If the item is a conditional raise of constraint error, then have
2212          --  a look at what check is being performed and ???
2213
2214          if Nkind (R_Cno) = N_Raise_Constraint_Error
2215            and then Present (Condition (R_Cno))
2216          then
2217             Cond := Condition (R_Cno);
2218
2219             if not Has_Dynamic_Range_Check (Ck_Node) then
2220                Insert_Action (Ck_Node, R_Cno);
2221
2222                if not Do_Static then
2223                   Set_Has_Dynamic_Range_Check (Ck_Node);
2224                end if;
2225             end if;
2226
2227             --  Output a warning if the condition is known to be True
2228
2229             if Is_Entity_Name (Cond)
2230               and then Entity (Cond) = Standard_True
2231             then
2232                --  Since an N_Range is technically not an expression, we have
2233                --  to set one of the bounds to C_E and then just flag the
2234                --  N_Range. The warning message will point to the lower bound
2235                --  and complain about a range, which seems OK.
2236
2237                if Nkind (Ck_Node) = N_Range then
2238                   Apply_Compile_Time_Constraint_Error
2239                     (Low_Bound (Ck_Node), "static range out of bounds of}?",
2240                      CE_Range_Check_Failed,
2241                      Ent => Target_Typ,
2242                      Typ => Target_Typ);
2243
2244                   Set_Raises_Constraint_Error (Ck_Node);
2245
2246                else
2247                   Apply_Compile_Time_Constraint_Error
2248                     (Ck_Node, "static value out of range of}?",
2249                      CE_Range_Check_Failed,
2250                      Ent => Target_Typ,
2251                      Typ => Target_Typ);
2252                end if;
2253
2254             --  If we were only doing a static check, or if checks are not
2255             --  on, then we want to delete the check, since it is not needed.
2256             --  We do this by replacing the if statement by a null statement
2257
2258             elsif Do_Static or else not Checks_On then
2259                Remove_Warning_Messages (R_Cno);
2260                Rewrite (R_Cno, Make_Null_Statement (Loc));
2261             end if;
2262
2263          else
2264             Install_Static_Check (R_Cno, Loc);
2265          end if;
2266       end loop;
2267    end Apply_Selected_Range_Checks;
2268
2269    -------------------------------
2270    -- Apply_Static_Length_Check --
2271    -------------------------------
2272
2273    procedure Apply_Static_Length_Check
2274      (Expr       : Node_Id;
2275       Target_Typ : Entity_Id;
2276       Source_Typ : Entity_Id := Empty)
2277    is
2278    begin
2279       Apply_Selected_Length_Checks
2280         (Expr, Target_Typ, Source_Typ, Do_Static => True);
2281    end Apply_Static_Length_Check;
2282
2283    -------------------------------------
2284    -- Apply_Subscript_Validity_Checks --
2285    -------------------------------------
2286
2287    procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2288       Sub : Node_Id;
2289
2290    begin
2291       pragma Assert (Nkind (Expr) = N_Indexed_Component);
2292
2293       --  Loop through subscripts
2294
2295       Sub := First (Expressions (Expr));
2296       while Present (Sub) loop
2297
2298          --  Check one subscript. Note that we do not worry about enumeration
2299          --  type with holes, since we will convert the value to a Pos value
2300          --  for the subscript, and that convert will do the necessary validity
2301          --  check.
2302
2303          Ensure_Valid (Sub, Holes_OK => True);
2304
2305          --  Move to next subscript
2306
2307          Sub := Next (Sub);
2308       end loop;
2309    end Apply_Subscript_Validity_Checks;
2310
2311    ----------------------------------
2312    -- Apply_Type_Conversion_Checks --
2313    ----------------------------------
2314
2315    procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2316       Target_Type : constant Entity_Id := Etype (N);
2317       Target_Base : constant Entity_Id := Base_Type (Target_Type);
2318       Expr        : constant Node_Id   := Expression (N);
2319       Expr_Type   : constant Entity_Id := Etype (Expr);
2320
2321    begin
2322       if Inside_A_Generic then
2323          return;
2324
2325       --  Skip these checks if serious errors detected, there are some nasty
2326       --  situations of incomplete trees that blow things up.
2327
2328       elsif Serious_Errors_Detected > 0 then
2329          return;
2330
2331       --  Scalar type conversions of the form Target_Type (Expr) require a
2332       --  range check if we cannot be sure that Expr is in the base type of
2333       --  Target_Typ and also that Expr is in the range of Target_Typ. These
2334       --  are not quite the same condition from an implementation point of
2335       --  view, but clearly the second includes the first.
2336
2337       elsif Is_Scalar_Type (Target_Type) then
2338          declare
2339             Conv_OK  : constant Boolean := Conversion_OK (N);
2340             --  If the Conversion_OK flag on the type conversion is set and no
2341             --  floating point type is involved in the type conversion then
2342             --  fixed point values must be read as integral values.
2343
2344             Float_To_Int : constant Boolean :=
2345                              Is_Floating_Point_Type (Expr_Type)
2346                                and then Is_Integer_Type (Target_Type);
2347
2348          begin
2349             if not Overflow_Checks_Suppressed (Target_Base)
2350               and then not
2351                 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
2352               and then not Float_To_Int
2353             then
2354                Activate_Overflow_Check (N);
2355             end if;
2356
2357             if not Range_Checks_Suppressed (Target_Type)
2358               and then not Range_Checks_Suppressed (Expr_Type)
2359             then
2360                if Float_To_Int then
2361                   Apply_Float_Conversion_Check (Expr, Target_Type);
2362                else
2363                   Apply_Scalar_Range_Check
2364                     (Expr, Target_Type, Fixed_Int => Conv_OK);
2365                end if;
2366             end if;
2367          end;
2368
2369       elsif Comes_From_Source (N)
2370         and then not Discriminant_Checks_Suppressed (Target_Type)
2371         and then Is_Record_Type (Target_Type)
2372         and then Is_Derived_Type (Target_Type)
2373         and then not Is_Tagged_Type (Target_Type)
2374         and then not Is_Constrained (Target_Type)
2375         and then Present (Stored_Constraint (Target_Type))
2376       then
2377          --  An unconstrained derived type may have inherited discriminant
2378          --  Build an actual discriminant constraint list using the stored
2379          --  constraint, to verify that the expression of the parent type
2380          --  satisfies the constraints imposed by the (unconstrained!)
2381          --  derived type. This applies to value conversions, not to view
2382          --  conversions of tagged types.
2383
2384          declare
2385             Loc         : constant Source_Ptr := Sloc (N);
2386             Cond        : Node_Id;
2387             Constraint  : Elmt_Id;
2388             Discr_Value : Node_Id;
2389             Discr       : Entity_Id;
2390
2391             New_Constraints : constant Elist_Id := New_Elmt_List;
2392             Old_Constraints : constant Elist_Id :=
2393                                 Discriminant_Constraint (Expr_Type);
2394
2395          begin
2396             Constraint := First_Elmt (Stored_Constraint (Target_Type));
2397             while Present (Constraint) loop
2398                Discr_Value := Node (Constraint);
2399
2400                if Is_Entity_Name (Discr_Value)
2401                  and then Ekind (Entity (Discr_Value)) = E_Discriminant
2402                then
2403                   Discr := Corresponding_Discriminant (Entity (Discr_Value));
2404
2405                   if Present (Discr)
2406                     and then Scope (Discr) = Base_Type (Expr_Type)
2407                   then
2408                      --  Parent is constrained by new discriminant. Obtain
2409                      --  Value of original discriminant in expression. If the
2410                      --  new discriminant has been used to constrain more than
2411                      --  one of the stored discriminants, this will provide the
2412                      --  required consistency check.
2413
2414                      Append_Elmt (
2415                         Make_Selected_Component (Loc,
2416                           Prefix =>
2417                             Duplicate_Subexpr_No_Checks
2418                               (Expr, Name_Req => True),
2419                           Selector_Name =>
2420                             Make_Identifier (Loc, Chars (Discr))),
2421                                 New_Constraints);
2422
2423                   else
2424                      --  Discriminant of more remote ancestor ???
2425
2426                      return;
2427                   end if;
2428
2429                --  Derived type definition has an explicit value for this
2430                --  stored discriminant.
2431
2432                else
2433                   Append_Elmt
2434                     (Duplicate_Subexpr_No_Checks (Discr_Value),
2435                      New_Constraints);
2436                end if;
2437
2438                Next_Elmt (Constraint);
2439             end loop;
2440
2441             --  Use the unconstrained expression type to retrieve the
2442             --  discriminants of the parent, and apply momentarily the
2443             --  discriminant constraint synthesized above.
2444
2445             Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2446             Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2447             Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2448
2449             Insert_Action (N,
2450               Make_Raise_Constraint_Error (Loc,
2451                 Condition => Cond,
2452                 Reason    => CE_Discriminant_Check_Failed));
2453          end;
2454
2455       --  For arrays, conversions are applied during expansion, to take into
2456       --  accounts changes of representation. The checks become range checks on
2457       --  the base type or length checks on the subtype, depending on whether
2458       --  the target type is unconstrained or constrained.
2459
2460       else
2461          null;
2462       end if;
2463    end Apply_Type_Conversion_Checks;
2464
2465    ----------------------------------------------
2466    -- Apply_Universal_Integer_Attribute_Checks --
2467    ----------------------------------------------
2468
2469    procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2470       Loc : constant Source_Ptr := Sloc (N);
2471       Typ : constant Entity_Id  := Etype (N);
2472
2473    begin
2474       if Inside_A_Generic then
2475          return;
2476
2477       --  Nothing to do if checks are suppressed
2478
2479       elsif Range_Checks_Suppressed (Typ)
2480         and then Overflow_Checks_Suppressed (Typ)
2481       then
2482          return;
2483
2484       --  Nothing to do if the attribute does not come from source. The
2485       --  internal attributes we generate of this type do not need checks,
2486       --  and furthermore the attempt to check them causes some circular
2487       --  elaboration orders when dealing with packed types.
2488
2489       elsif not Comes_From_Source (N) then
2490          return;
2491
2492       --  If the prefix is a selected component that depends on a discriminant
2493       --  the check may improperly expose a discriminant instead of using
2494       --  the bounds of the object itself. Set the type of the attribute to
2495       --  the base type of the context, so that a check will be imposed when
2496       --  needed (e.g. if the node appears as an index).
2497
2498       elsif Nkind (Prefix (N)) = N_Selected_Component
2499         and then Ekind (Typ) = E_Signed_Integer_Subtype
2500         and then Depends_On_Discriminant (Scalar_Range (Typ))
2501       then
2502          Set_Etype (N, Base_Type (Typ));
2503
2504       --  Otherwise, replace the attribute node with a type conversion node
2505       --  whose expression is the attribute, retyped to universal integer, and
2506       --  whose subtype mark is the target type. The call to analyze this
2507       --  conversion will set range and overflow checks as required for proper
2508       --  detection of an out of range value.
2509
2510       else
2511          Set_Etype    (N, Universal_Integer);
2512          Set_Analyzed (N, True);
2513
2514          Rewrite (N,
2515            Make_Type_Conversion (Loc,
2516              Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2517              Expression   => Relocate_Node (N)));
2518
2519          Analyze_And_Resolve (N, Typ);
2520          return;
2521       end if;
2522    end Apply_Universal_Integer_Attribute_Checks;
2523
2524    -------------------------------
2525    -- Build_Discriminant_Checks --
2526    -------------------------------
2527
2528    function Build_Discriminant_Checks
2529      (N     : Node_Id;
2530       T_Typ : Entity_Id) return Node_Id
2531    is
2532       Loc      : constant Source_Ptr := Sloc (N);
2533       Cond     : Node_Id;
2534       Disc     : Elmt_Id;
2535       Disc_Ent : Entity_Id;
2536       Dref     : Node_Id;
2537       Dval     : Node_Id;
2538
2539       function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2540
2541       ----------------------------------
2542       -- Aggregate_Discriminant_Value --
2543       ----------------------------------
2544
2545       function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2546          Assoc : Node_Id;
2547
2548       begin
2549          --  The aggregate has been normalized with named associations. We use
2550          --  the Chars field to locate the discriminant to take into account
2551          --  discriminants in derived types, which carry the same name as those
2552          --  in the parent.
2553
2554          Assoc := First (Component_Associations (N));
2555          while Present (Assoc) loop
2556             if Chars (First (Choices (Assoc))) = Chars (Disc) then
2557                return Expression (Assoc);
2558             else
2559                Next (Assoc);
2560             end if;
2561          end loop;
2562
2563          --  Discriminant must have been found in the loop above
2564
2565          raise Program_Error;
2566       end Aggregate_Discriminant_Val;
2567
2568    --  Start of processing for Build_Discriminant_Checks
2569
2570    begin
2571       --  Loop through discriminants evolving the condition
2572
2573       Cond := Empty;
2574       Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2575
2576       --  For a fully private type, use the discriminants of the parent type
2577
2578       if Is_Private_Type (T_Typ)
2579         and then No (Full_View (T_Typ))
2580       then
2581          Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2582       else
2583          Disc_Ent := First_Discriminant (T_Typ);
2584       end if;
2585
2586       while Present (Disc) loop
2587          Dval := Node (Disc);
2588
2589          if Nkind (Dval) = N_Identifier
2590            and then Ekind (Entity (Dval)) = E_Discriminant
2591          then
2592             Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2593          else
2594             Dval := Duplicate_Subexpr_No_Checks (Dval);
2595          end if;
2596
2597          --  If we have an Unchecked_Union node, we can infer the discriminants
2598          --  of the node.
2599
2600          if Is_Unchecked_Union (Base_Type (T_Typ)) then
2601             Dref := New_Copy (
2602               Get_Discriminant_Value (
2603                 First_Discriminant (T_Typ),
2604                 T_Typ,
2605                 Stored_Constraint (T_Typ)));
2606
2607          elsif Nkind (N) = N_Aggregate then
2608             Dref :=
2609                Duplicate_Subexpr_No_Checks
2610                  (Aggregate_Discriminant_Val (Disc_Ent));
2611
2612          else
2613             Dref :=
2614               Make_Selected_Component (Loc,
2615                 Prefix =>
2616                   Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2617                 Selector_Name =>
2618                   Make_Identifier (Loc, Chars (Disc_Ent)));
2619
2620             Set_Is_In_Discriminant_Check (Dref);
2621          end if;
2622
2623          Evolve_Or_Else (Cond,
2624            Make_Op_Ne (Loc,
2625              Left_Opnd => Dref,
2626              Right_Opnd => Dval));
2627
2628          Next_Elmt (Disc);
2629          Next_Discriminant (Disc_Ent);
2630       end loop;
2631
2632       return Cond;
2633    end Build_Discriminant_Checks;
2634
2635    ------------------
2636    -- Check_Needed --
2637    ------------------
2638
2639    function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2640       N : Node_Id;
2641       P : Node_Id;
2642       K : Node_Kind;
2643       L : Node_Id;
2644       R : Node_Id;
2645
2646    begin
2647       --  Always check if not simple entity
2648
2649       if Nkind (Nod) not in N_Has_Entity
2650         or else not Comes_From_Source (Nod)
2651       then
2652          return True;
2653       end if;
2654
2655       --  Look up tree for short circuit
2656
2657       N := Nod;
2658       loop
2659          P := Parent (N);
2660          K := Nkind (P);
2661
2662          --  Done if out of subexpression (note that we allow generated stuff
2663          --  such as itype declarations in this context, to keep the loop going
2664          --  since we may well have generated such stuff in complex situations.
2665          --  Also done if no parent (probably an error condition, but no point
2666          --  in behaving nasty if we find it!)
2667
2668          if No (P)
2669            or else (K not in N_Subexpr and then Comes_From_Source (P))
2670          then
2671             return True;
2672
2673          --  Or/Or Else case, where test is part of the right operand, or is
2674          --  part of one of the actions associated with the right operand, and
2675          --  the left operand is an equality test.
2676
2677          elsif K = N_Op_Or then
2678             exit when N = Right_Opnd (P)
2679               and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2680
2681          elsif K = N_Or_Else then
2682             exit when (N = Right_Opnd (P)
2683                         or else
2684                           (Is_List_Member (N)
2685                              and then List_Containing (N) = Actions (P)))
2686               and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2687
2688          --  Similar test for the And/And then case, where the left operand
2689          --  is an inequality test.
2690
2691          elsif K = N_Op_And then
2692             exit when N = Right_Opnd (P)
2693               and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2694
2695          elsif K = N_And_Then then
2696             exit when (N = Right_Opnd (P)
2697                         or else
2698                           (Is_List_Member (N)
2699                              and then List_Containing (N) = Actions (P)))
2700               and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2701          end if;
2702
2703          N := P;
2704       end loop;
2705
2706       --  If we fall through the loop, then we have a conditional with an
2707       --  appropriate test as its left operand. So test further.
2708
2709       L := Left_Opnd (P);
2710       R := Right_Opnd (L);
2711       L := Left_Opnd (L);
2712
2713       --  Left operand of test must match original variable
2714
2715       if Nkind (L) not in N_Has_Entity
2716         or else Entity (L) /= Entity (Nod)
2717       then
2718          return True;
2719       end if;
2720
2721       --  Right operand of test must be key value (zero or null)
2722
2723       case Check is
2724          when Access_Check =>
2725             if not Known_Null (R) then
2726                return True;
2727             end if;
2728
2729          when Division_Check =>
2730             if not Compile_Time_Known_Value (R)
2731               or else Expr_Value (R) /= Uint_0
2732             then
2733                return True;
2734             end if;
2735
2736          when others =>
2737             raise Program_Error;
2738       end case;
2739
2740       --  Here we have the optimizable case, warn if not short-circuited
2741
2742       if K = N_Op_And or else K = N_Op_Or then
2743          case Check is
2744             when Access_Check =>
2745                Error_Msg_N
2746                  ("Constraint_Error may be raised (access check)?",
2747                   Parent (Nod));
2748             when Division_Check =>
2749                Error_Msg_N
2750                  ("Constraint_Error may be raised (zero divide)?",
2751                   Parent (Nod));
2752
2753             when others =>
2754                raise Program_Error;
2755          end case;
2756
2757          if K = N_Op_And then
2758             Error_Msg_N -- CODEFIX
2759               ("use `AND THEN` instead of AND?", P);
2760          else
2761             Error_Msg_N -- CODEFIX
2762               ("use `OR ELSE` instead of OR?", P);
2763          end if;
2764
2765          --  If not short-circuited, we need the ckeck
2766
2767          return True;
2768
2769       --  If short-circuited, we can omit the check
2770
2771       else
2772          return False;
2773       end if;
2774    end Check_Needed;
2775
2776    -----------------------------------
2777    -- Check_Valid_Lvalue_Subscripts --
2778    -----------------------------------
2779
2780    procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2781    begin
2782       --  Skip this if range checks are suppressed
2783
2784       if Range_Checks_Suppressed (Etype (Expr)) then
2785          return;
2786
2787       --  Only do this check for expressions that come from source. We assume
2788       --  that expander generated assignments explicitly include any necessary
2789       --  checks. Note that this is not just an optimization, it avoids
2790       --  infinite recursions!
2791
2792       elsif not Comes_From_Source (Expr) then
2793          return;
2794
2795       --  For a selected component, check the prefix
2796
2797       elsif Nkind (Expr) = N_Selected_Component then
2798          Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2799          return;
2800
2801       --  Case of indexed component
2802
2803       elsif Nkind (Expr) = N_Indexed_Component then
2804          Apply_Subscript_Validity_Checks (Expr);
2805
2806          --  Prefix may itself be or contain an indexed component, and these
2807          --  subscripts need checking as well.
2808
2809          Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2810       end if;
2811    end Check_Valid_Lvalue_Subscripts;
2812
2813    ----------------------------------
2814    -- Null_Exclusion_Static_Checks --
2815    ----------------------------------
2816
2817    procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2818       Error_Node : Node_Id;
2819       Expr       : Node_Id;
2820       Has_Null   : constant Boolean := Has_Null_Exclusion (N);
2821       K          : constant Node_Kind := Nkind (N);
2822       Typ        : Entity_Id;
2823
2824    begin
2825       pragma Assert
2826         (K = N_Component_Declaration
2827            or else K = N_Discriminant_Specification
2828            or else K = N_Function_Specification
2829            or else K = N_Object_Declaration
2830            or else K = N_Parameter_Specification);
2831
2832       if K = N_Function_Specification then
2833          Typ := Etype (Defining_Entity (N));
2834       else
2835          Typ := Etype (Defining_Identifier (N));
2836       end if;
2837
2838       case K is
2839          when N_Component_Declaration =>
2840             if Present (Access_Definition (Component_Definition (N))) then
2841                Error_Node := Component_Definition (N);
2842             else
2843                Error_Node := Subtype_Indication (Component_Definition (N));
2844             end if;
2845
2846          when N_Discriminant_Specification =>
2847             Error_Node    := Discriminant_Type (N);
2848
2849          when N_Function_Specification =>
2850             Error_Node    := Result_Definition (N);
2851
2852          when N_Object_Declaration =>
2853             Error_Node    := Object_Definition (N);
2854
2855          when N_Parameter_Specification =>
2856             Error_Node    := Parameter_Type (N);
2857
2858          when others =>
2859             raise Program_Error;
2860       end case;
2861
2862       if Has_Null then
2863
2864          --  Enforce legality rule 3.10 (13): A null exclusion can only be
2865          --  applied to an access [sub]type.
2866
2867          if not Is_Access_Type (Typ) then
2868             Error_Msg_N
2869               ("`NOT NULL` allowed only for an access type", Error_Node);
2870
2871          --  Enforce legality rule RM 3.10(14/1): A null exclusion can only
2872          --  be applied to a [sub]type that does not exclude null already.
2873
2874          elsif Can_Never_Be_Null (Typ)
2875            and then Comes_From_Source (Typ)
2876          then
2877             Error_Msg_NE
2878               ("`NOT NULL` not allowed (& already excludes null)",
2879                Error_Node, Typ);
2880          end if;
2881       end if;
2882
2883       --  Check that null-excluding objects are always initialized, except for
2884       --  deferred constants, for which the expression will appear in the full
2885       --  declaration.
2886
2887       if K = N_Object_Declaration
2888         and then No (Expression (N))
2889         and then not Constant_Present (N)
2890         and then not No_Initialization (N)
2891       then
2892          --  Add an expression that assigns null. This node is needed by
2893          --  Apply_Compile_Time_Constraint_Error, which will replace this with
2894          --  a Constraint_Error node.
2895
2896          Set_Expression (N, Make_Null (Sloc (N)));
2897          Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2898
2899          Apply_Compile_Time_Constraint_Error
2900            (N      => Expression (N),
2901             Msg    => "(Ada 2005) null-excluding objects must be initialized?",
2902             Reason => CE_Null_Not_Allowed);
2903       end if;
2904
2905       --  Check that a null-excluding component, formal or object is not being
2906       --  assigned a null value. Otherwise generate a warning message and
2907       --  replace Expression (N) by an N_Constraint_Error node.
2908
2909       if K /= N_Function_Specification then
2910          Expr := Expression (N);
2911
2912          if Present (Expr) and then Known_Null (Expr) then
2913             case K is
2914                when N_Component_Declaration      |
2915                     N_Discriminant_Specification =>
2916                   Apply_Compile_Time_Constraint_Error
2917                     (N      => Expr,
2918                      Msg    => "(Ada 2005) null not allowed " &
2919                                "in null-excluding components?",
2920                      Reason => CE_Null_Not_Allowed);
2921
2922                when N_Object_Declaration =>
2923                   Apply_Compile_Time_Constraint_Error
2924                     (N      => Expr,
2925                      Msg    => "(Ada 2005) null not allowed " &
2926                                "in null-excluding objects?",
2927                      Reason => CE_Null_Not_Allowed);
2928
2929                when N_Parameter_Specification =>
2930                   Apply_Compile_Time_Constraint_Error
2931                     (N      => Expr,
2932                      Msg    => "(Ada 2005) null not allowed " &
2933                                "in null-excluding formals?",
2934                      Reason => CE_Null_Not_Allowed);
2935
2936                when others =>
2937                   null;
2938             end case;
2939          end if;
2940       end if;
2941    end Null_Exclusion_Static_Checks;
2942
2943    ----------------------------------
2944    -- Conditional_Statements_Begin --
2945    ----------------------------------
2946
2947    procedure Conditional_Statements_Begin is
2948    begin
2949       Saved_Checks_TOS := Saved_Checks_TOS + 1;
2950
2951       --  If stack overflows, kill all checks, that way we know to simply reset
2952       --  the number of saved checks to zero on return. This should never occur
2953       --  in practice.
2954
2955       if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2956          Kill_All_Checks;
2957
2958       --  In the normal case, we just make a new stack entry saving the current
2959       --  number of saved checks for a later restore.
2960
2961       else
2962          Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2963
2964          if Debug_Flag_CC then
2965             w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2966                Num_Saved_Checks);
2967          end if;
2968       end if;
2969    end Conditional_Statements_Begin;
2970
2971    --------------------------------
2972    -- Conditional_Statements_End --
2973    --------------------------------
2974
2975    procedure Conditional_Statements_End is
2976    begin
2977       pragma Assert (Saved_Checks_TOS > 0);
2978
2979       --  If the saved checks stack overflowed, then we killed all checks, so
2980       --  setting the number of saved checks back to zero is correct. This
2981       --  should never occur in practice.
2982
2983       if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2984          Num_Saved_Checks := 0;
2985
2986       --  In the normal case, restore the number of saved checks from the top
2987       --  stack entry.
2988
2989       else
2990          Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
2991          if Debug_Flag_CC then
2992             w ("Conditional_Statements_End: Num_Saved_Checks = ",
2993                Num_Saved_Checks);
2994          end if;
2995       end if;
2996
2997       Saved_Checks_TOS := Saved_Checks_TOS - 1;
2998    end Conditional_Statements_End;
2999
3000    ---------------------
3001    -- Determine_Range --
3002    ---------------------
3003
3004    Cache_Size : constant := 2 ** 10;
3005    type Cache_Index is range 0 .. Cache_Size - 1;
3006    --  Determine size of below cache (power of 2 is more efficient!)
3007
3008    Determine_Range_Cache_N  : array (Cache_Index) of Node_Id;
3009    Determine_Range_Cache_V  : array (Cache_Index) of Boolean;
3010    Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
3011    Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
3012    --  The above arrays are used to implement a small direct cache for
3013    --  Determine_Range calls. Because of the way Determine_Range recursively
3014    --  traces subexpressions, and because overflow checking calls the routine
3015    --  on the way up the tree, a quadratic behavior can otherwise be
3016    --  encountered in large expressions. The cache entry for node N is stored
3017    --  in the (N mod Cache_Size) entry, and can be validated by checking the
3018    --  actual node value stored there. The Range_Cache_V array records the
3019    --  setting of Assume_Valid for the cache entry.
3020
3021    procedure Determine_Range
3022      (N            : Node_Id;
3023       OK           : out Boolean;
3024       Lo           : out Uint;
3025       Hi           : out Uint;
3026       Assume_Valid : Boolean := False)
3027    is
3028       Typ : Entity_Id := Etype (N);
3029       --  Type to use, may get reset to base type for possibly invalid entity
3030
3031       Lo_Left : Uint;
3032       Hi_Left : Uint;
3033       --  Lo and Hi bounds of left operand
3034
3035       Lo_Right : Uint;
3036       Hi_Right : Uint;
3037       --  Lo and Hi bounds of right (or only) operand
3038
3039       Bound : Node_Id;
3040       --  Temp variable used to hold a bound node
3041
3042       Hbound : Uint;
3043       --  High bound of base type of expression
3044
3045       Lor : Uint;
3046       Hir : Uint;
3047       --  Refined values for low and high bounds, after tightening
3048
3049       OK1 : Boolean;
3050       --  Used in lower level calls to indicate if call succeeded
3051
3052       Cindex : Cache_Index;
3053       --  Used to search cache
3054
3055       function OK_Operands return Boolean;
3056       --  Used for binary operators. Determines the ranges of the left and
3057       --  right operands, and if they are both OK, returns True, and puts
3058       --  the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
3059
3060       -----------------
3061       -- OK_Operands --
3062       -----------------
3063
3064       function OK_Operands return Boolean is
3065       begin
3066          Determine_Range
3067            (Left_Opnd  (N), OK1, Lo_Left,  Hi_Left, Assume_Valid);
3068
3069          if not OK1 then
3070             return False;
3071          end if;
3072
3073          Determine_Range
3074            (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3075          return OK1;
3076       end OK_Operands;
3077
3078    --  Start of processing for Determine_Range
3079
3080    begin
3081       --  Prevent junk warnings by initializing range variables
3082
3083       Lo  := No_Uint;
3084       Hi  := No_Uint;
3085       Lor := No_Uint;
3086       Hir := No_Uint;
3087
3088       --  If type is not defined, we can't determine its range
3089
3090       if No (Typ)
3091
3092         --  We don't deal with anything except discrete types
3093
3094         or else not Is_Discrete_Type (Typ)
3095
3096         --  Ignore type for which an error has been posted, since range in
3097         --  this case may well be a bogosity deriving from the error. Also
3098         --  ignore if error posted on the reference node.
3099
3100         or else Error_Posted (N) or else Error_Posted (Typ)
3101       then
3102          OK := False;
3103          return;
3104       end if;
3105
3106       --  For all other cases, we can determine the range
3107
3108       OK := True;
3109
3110       --  If value is compile time known, then the possible range is the one
3111       --  value that we know this expression definitely has!
3112
3113       if Compile_Time_Known_Value (N) then
3114          Lo := Expr_Value (N);
3115          Hi := Lo;
3116          return;
3117       end if;
3118
3119       --  Return if already in the cache
3120
3121       Cindex := Cache_Index (N mod Cache_Size);
3122
3123       if Determine_Range_Cache_N (Cindex) = N
3124            and then
3125          Determine_Range_Cache_V (Cindex) = Assume_Valid
3126       then
3127          Lo := Determine_Range_Cache_Lo (Cindex);
3128          Hi := Determine_Range_Cache_Hi (Cindex);
3129          return;
3130       end if;
3131
3132       --  Otherwise, start by finding the bounds of the type of the expression,
3133       --  the value cannot be outside this range (if it is, then we have an
3134       --  overflow situation, which is a separate check, we are talking here
3135       --  only about the expression value).
3136
3137       --  First a check, never try to find the bounds of a generic type, since
3138       --  these bounds are always junk values, and it is only valid to look at
3139       --  the bounds in an instance.
3140
3141       if Is_Generic_Type (Typ) then
3142          OK := False;
3143          return;
3144       end if;
3145
3146       --  First step, change to use base type unless we know the value is valid
3147
3148       if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
3149         or else Assume_No_Invalid_Values
3150         or else Assume_Valid
3151       then
3152          null;
3153       else
3154          Typ := Underlying_Type (Base_Type (Typ));
3155       end if;
3156
3157       --  We use the actual bound unless it is dynamic, in which case use the
3158       --  corresponding base type bound if possible. If we can't get a bound
3159       --  then we figure we can't determine the range (a peculiar case, that
3160       --  perhaps cannot happen, but there is no point in bombing in this
3161       --  optimization circuit.
3162
3163       --  First the low bound
3164
3165       Bound := Type_Low_Bound (Typ);
3166
3167       if Compile_Time_Known_Value (Bound) then
3168          Lo := Expr_Value (Bound);
3169
3170       elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
3171          Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
3172
3173       else
3174          OK := False;
3175          return;
3176       end if;
3177
3178       --  Now the high bound
3179
3180       Bound := Type_High_Bound (Typ);
3181
3182       --  We need the high bound of the base type later on, and this should
3183       --  always be compile time known. Again, it is not clear that this
3184       --  can ever be false, but no point in bombing.
3185
3186       if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
3187          Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
3188          Hi := Hbound;
3189
3190       else
3191          OK := False;
3192          return;
3193       end if;
3194
3195       --  If we have a static subtype, then that may have a tighter bound so
3196       --  use the upper bound of the subtype instead in this case.
3197
3198       if Compile_Time_Known_Value (Bound) then
3199          Hi := Expr_Value (Bound);
3200       end if;
3201
3202       --  We may be able to refine this value in certain situations. If any
3203       --  refinement is possible, then Lor and Hir are set to possibly tighter
3204       --  bounds, and OK1 is set to True.
3205
3206       case Nkind (N) is
3207
3208          --  For unary plus, result is limited by range of operand
3209
3210          when N_Op_Plus =>
3211             Determine_Range
3212               (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
3213
3214          --  For unary minus, determine range of operand, and negate it
3215
3216          when N_Op_Minus =>
3217             Determine_Range
3218               (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
3219
3220             if OK1 then
3221                Lor := -Hi_Right;
3222                Hir := -Lo_Right;
3223             end if;
3224
3225          --  For binary addition, get range of each operand and do the
3226          --  addition to get the result range.
3227
3228          when N_Op_Add =>
3229             if OK_Operands then
3230                Lor := Lo_Left + Lo_Right;
3231                Hir := Hi_Left + Hi_Right;
3232             end if;
3233
3234          --  Division is tricky. The only case we consider is where the right
3235          --  operand is a positive constant, and in this case we simply divide
3236          --  the bounds of the left operand
3237
3238          when N_Op_Divide =>
3239             if OK_Operands then
3240                if Lo_Right = Hi_Right
3241                  and then Lo_Right > 0
3242                then
3243                   Lor := Lo_Left / Lo_Right;
3244                   Hir := Hi_Left / Lo_Right;
3245
3246                else
3247                   OK1 := False;
3248                end if;
3249             end if;
3250
3251          --  For binary subtraction, get range of each operand and do the worst
3252          --  case subtraction to get the result range.
3253
3254          when N_Op_Subtract =>
3255             if OK_Operands then
3256                Lor := Lo_Left - Hi_Right;
3257                Hir := Hi_Left - Lo_Right;
3258             end if;
3259
3260          --  For MOD, if right operand is a positive constant, then result must
3261          --  be in the allowable range of mod results.
3262
3263          when N_Op_Mod =>
3264             if OK_Operands then
3265                if Lo_Right = Hi_Right
3266                  and then Lo_Right /= 0
3267                then
3268                   if Lo_Right > 0 then
3269                      Lor := Uint_0;
3270                      Hir := Lo_Right - 1;
3271
3272                   else -- Lo_Right < 0
3273                      Lor := Lo_Right + 1;
3274                      Hir := Uint_0;
3275                   end if;
3276
3277                else
3278                   OK1 := False;
3279                end if;
3280             end if;
3281
3282          --  For REM, if right operand is a positive constant, then result must
3283          --  be in the allowable range of mod results.
3284
3285          when N_Op_Rem =>
3286             if OK_Operands then
3287                if Lo_Right = Hi_Right
3288                  and then Lo_Right /= 0
3289                then
3290                   declare
3291                      Dval : constant Uint := (abs Lo_Right) - 1;
3292
3293                   begin
3294                      --  The sign of the result depends on the sign of the
3295                      --  dividend (but not on the sign of the divisor, hence
3296                      --  the abs operation above).
3297
3298                      if Lo_Left < 0 then
3299                         Lor := -Dval;
3300                      else
3301                         Lor := Uint_0;
3302                      end if;
3303
3304                      if Hi_Left < 0 then
3305                         Hir := Uint_0;
3306                      else
3307                         Hir := Dval;
3308                      end if;
3309                   end;
3310
3311                else
3312                   OK1 := False;
3313                end if;
3314             end if;
3315
3316          --  Attribute reference cases
3317
3318          when N_Attribute_Reference =>
3319             case Attribute_Name (N) is
3320
3321                --  For Pos/Val attributes, we can refine the range using the
3322                --  possible range of values of the attribute expression.
3323
3324                when Name_Pos | Name_Val =>
3325                   Determine_Range
3326                     (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
3327
3328                --  For Length attribute, use the bounds of the corresponding
3329                --  index type to refine the range.
3330
3331                when Name_Length =>
3332                   declare
3333                      Atyp : Entity_Id := Etype (Prefix (N));
3334                      Inum : Nat;
3335                      Indx : Node_Id;
3336
3337                      LL, LU : Uint;
3338                      UL, UU : Uint;
3339
3340                   begin
3341                      if Is_Access_Type (Atyp) then
3342                         Atyp := Designated_Type (Atyp);
3343                      end if;
3344
3345                      --  For string literal, we know exact value
3346
3347                      if Ekind (Atyp) = E_String_Literal_Subtype then
3348                         OK := True;
3349                         Lo := String_Literal_Length (Atyp);
3350                         Hi := String_Literal_Length (Atyp);
3351                         return;
3352                      end if;
3353
3354                      --  Otherwise check for expression given
3355
3356                      if No (Expressions (N)) then
3357                         Inum := 1;
3358                      else
3359                         Inum :=
3360                           UI_To_Int (Expr_Value (First (Expressions (N))));
3361                      end if;
3362
3363                      Indx := First_Index (Atyp);
3364                      for J in 2 .. Inum loop
3365                         Indx := Next_Index (Indx);
3366                      end loop;
3367
3368                      --  If the index type is a formal type or derived from
3369                      --  one, the bounds are not static.
3370
3371                      if Is_Generic_Type (Root_Type (Etype (Indx))) then
3372                         OK := False;
3373                         return;
3374                      end if;
3375
3376                      Determine_Range
3377                        (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
3378                         Assume_Valid);
3379
3380                      if OK1 then
3381                         Determine_Range
3382                           (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
3383                            Assume_Valid);
3384
3385                         if OK1 then
3386
3387                            --  The maximum value for Length is the biggest
3388                            --  possible gap between the values of the bounds.
3389                            --  But of course, this value cannot be negative.
3390
3391                            Hir := UI_Max (Uint_0, UU - LL + 1);
3392
3393                            --  For constrained arrays, the minimum value for
3394                            --  Length is taken from the actual value of the
3395                            --  bounds, since the index will be exactly of this
3396                            --  subtype.
3397
3398                            if Is_Constrained (Atyp) then
3399                               Lor := UI_Max (Uint_0, UL - LU + 1);
3400
3401                            --  For an unconstrained array, the minimum value
3402                            --  for length is always zero.
3403
3404                            else
3405                               Lor := Uint_0;
3406                            end if;
3407                         end if;
3408                      end if;
3409                   end;
3410
3411                --  No special handling for other attributes
3412                --  Probably more opportunities exist here???
3413
3414                when others =>
3415                   OK1 := False;
3416
3417             end case;
3418
3419          --  For type conversion from one discrete type to another, we can
3420          --  refine the range using the converted value.
3421
3422          when N_Type_Conversion =>
3423             Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
3424
3425          --  Nothing special to do for all other expression kinds
3426
3427          when others =>
3428             OK1 := False;
3429             Lor := No_Uint;
3430             Hir := No_Uint;
3431       end case;
3432
3433       --  At this stage, if OK1 is true, then we know that the actual result of
3434       --  the computed expression is in the range Lor .. Hir. We can use this
3435       --  to restrict the possible range of results.
3436
3437       if OK1 then
3438
3439          --  If the refined value of the low bound is greater than the type
3440          --  high bound, then reset it to the more restrictive value. However,
3441          --  we do NOT do this for the case of a modular type where the
3442          --  possible upper bound on the value is above the base type high
3443          --  bound, because that means the result could wrap.
3444
3445          if Lor > Lo
3446            and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
3447          then
3448             Lo := Lor;
3449          end if;
3450
3451          --  Similarly, if the refined value of the high bound is less than the
3452          --  value so far, then reset it to the more restrictive value. Again,
3453          --  we do not do this if the refined low bound is negative for a
3454          --  modular type, since this would wrap.
3455
3456          if Hir < Hi
3457            and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
3458          then
3459             Hi := Hir;
3460          end if;
3461       end if;
3462
3463       --  Set cache entry for future call and we are all done
3464
3465       Determine_Range_Cache_N  (Cindex) := N;
3466       Determine_Range_Cache_V  (Cindex) := Assume_Valid;
3467       Determine_Range_Cache_Lo (Cindex) := Lo;
3468       Determine_Range_Cache_Hi (Cindex) := Hi;
3469       return;
3470
3471    --  If any exception occurs, it means that we have some bug in the compiler,
3472    --  possibly triggered by a previous error, or by some unforeseen peculiar
3473    --  occurrence. However, this is only an optimization attempt, so there is
3474    --  really no point in crashing the compiler. Instead we just decide, too
3475    --  bad, we can't figure out a range in this case after all.
3476
3477    exception
3478       when others =>
3479
3480          --  Debug flag K disables this behavior (useful for debugging)
3481
3482          if Debug_Flag_K then
3483             raise;
3484          else
3485             OK := False;
3486             Lo := No_Uint;
3487             Hi := No_Uint;
3488             return;
3489          end if;
3490    end Determine_Range;
3491
3492    ------------------------------------
3493    -- Discriminant_Checks_Suppressed --
3494    ------------------------------------
3495
3496    function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3497    begin
3498       if Present (E) then
3499          if Is_Unchecked_Union (E) then
3500             return True;
3501          elsif Checks_May_Be_Suppressed (E) then
3502             return Is_Check_Suppressed (E, Discriminant_Check);
3503          end if;
3504       end if;
3505
3506       return Scope_Suppress (Discriminant_Check);
3507    end Discriminant_Checks_Suppressed;
3508
3509    --------------------------------
3510    -- Division_Checks_Suppressed --
3511    --------------------------------
3512
3513    function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3514    begin
3515       if Present (E) and then Checks_May_Be_Suppressed (E) then
3516          return Is_Check_Suppressed (E, Division_Check);
3517       else
3518          return Scope_Suppress (Division_Check);
3519       end if;
3520    end Division_Checks_Suppressed;
3521
3522    -----------------------------------
3523    -- Elaboration_Checks_Suppressed --
3524    -----------------------------------
3525
3526    function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3527    begin
3528       --  The complication in this routine is that if we are in the dynamic
3529       --  model of elaboration, we also check All_Checks, since All_Checks
3530       --  does not set Elaboration_Check explicitly.
3531
3532       if Present (E) then
3533          if Kill_Elaboration_Checks (E) then
3534             return True;
3535
3536          elsif Checks_May_Be_Suppressed (E) then
3537             if Is_Check_Suppressed (E, Elaboration_Check) then
3538                return True;
3539             elsif Dynamic_Elaboration_Checks then
3540                return Is_Check_Suppressed (E, All_Checks);
3541             else
3542                return False;
3543             end if;
3544          end if;
3545       end if;
3546
3547       if Scope_Suppress (Elaboration_Check) then
3548          return True;
3549       elsif Dynamic_Elaboration_Checks then
3550          return Scope_Suppress (All_Checks);
3551       else
3552          return False;
3553       end if;
3554    end Elaboration_Checks_Suppressed;
3555
3556    ---------------------------
3557    -- Enable_Overflow_Check --
3558    ---------------------------
3559
3560    procedure Enable_Overflow_Check (N : Node_Id) is
3561       Typ : constant Entity_Id  := Base_Type (Etype (N));
3562       Chk : Nat;
3563       OK  : Boolean;
3564       Ent : Entity_Id;
3565       Ofs : Uint;
3566       Lo  : Uint;
3567       Hi  : Uint;
3568
3569    begin
3570       if Debug_Flag_CC then
3571          w ("Enable_Overflow_Check for node ", Int (N));
3572          Write_Str ("  Source location = ");
3573          wl (Sloc (N));
3574          pg (Union_Id (N));
3575       end if;
3576
3577       --  No check if overflow checks suppressed for type of node
3578
3579       if Present (Etype (N))
3580         and then Overflow_Checks_Suppressed (Etype (N))
3581       then
3582          return;
3583
3584       --  Nothing to do for unsigned integer types, which do not overflow
3585
3586       elsif Is_Modular_Integer_Type (Typ) then
3587          return;
3588
3589       --  Nothing to do if the range of the result is known OK. We skip this
3590       --  for conversions, since the caller already did the check, and in any
3591       --  case the condition for deleting the check for a type conversion is
3592       --  different.
3593
3594       elsif Nkind (N) /= N_Type_Conversion then
3595          Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
3596
3597          --  Note in the test below that we assume that the range is not OK
3598          --  if a bound of the range is equal to that of the type. That's not
3599          --  quite accurate but we do this for the following reasons:
3600
3601          --   a) The way that Determine_Range works, it will typically report
3602          --      the bounds of the value as being equal to the bounds of the
3603          --      type, because it either can't tell anything more precise, or
3604          --      does not think it is worth the effort to be more precise.
3605
3606          --   b) It is very unusual to have a situation in which this would
3607          --      generate an unnecessary overflow check (an example would be
3608          --      a subtype with a range 0 .. Integer'Last - 1 to which the
3609          --      literal value one is added).
3610
3611          --   c) The alternative is a lot of special casing in this routine
3612          --      which would partially duplicate Determine_Range processing.
3613
3614          if OK
3615            and then Lo > Expr_Value (Type_Low_Bound  (Typ))
3616            and then Hi < Expr_Value (Type_High_Bound (Typ))
3617          then
3618             if Debug_Flag_CC then
3619                w ("No overflow check required");
3620             end if;
3621
3622             return;
3623          end if;
3624       end if;
3625
3626       --  If not in optimizing mode, set flag and we are done. We are also done
3627       --  (and just set the flag) if the type is not a discrete type, since it
3628       --  is not worth the effort to eliminate checks for other than discrete
3629       --  types. In addition, we take this same path if we have stored the
3630       --  maximum number of checks possible already (a very unlikely situation,
3631       --  but we do not want to blow up!)
3632
3633       if Optimization_Level = 0
3634         or else not Is_Discrete_Type (Etype (N))
3635         or else Num_Saved_Checks = Saved_Checks'Last
3636       then
3637          Activate_Overflow_Check (N);
3638
3639          if Debug_Flag_CC then
3640             w ("Optimization off");
3641          end if;
3642
3643          return;
3644       end if;
3645
3646       --  Otherwise evaluate and check the expression
3647
3648       Find_Check
3649         (Expr        => N,
3650          Check_Type  => 'O',
3651          Target_Type => Empty,
3652          Entry_OK    => OK,
3653          Check_Num   => Chk,
3654          Ent         => Ent,
3655          Ofs         => Ofs);
3656
3657       if Debug_Flag_CC then
3658          w ("Called Find_Check");
3659          w ("  OK = ", OK);
3660
3661          if OK then
3662             w ("  Check_Num = ", Chk);
3663             w ("  Ent       = ", Int (Ent));
3664             Write_Str ("  Ofs       = ");
3665             pid (Ofs);
3666          end if;
3667       end if;
3668
3669       --  If check is not of form to optimize, then set flag and we are done
3670
3671       if not OK then
3672          Activate_Overflow_Check (N);
3673          return;
3674       end if;
3675
3676       --  If check is already performed, then return without setting flag
3677
3678       if Chk /= 0 then
3679          if Debug_Flag_CC then
3680             w ("Check suppressed!");
3681          end if;
3682
3683          return;
3684       end if;
3685
3686       --  Here we will make a new entry for the new check
3687
3688       Activate_Overflow_Check (N);
3689       Num_Saved_Checks := Num_Saved_Checks + 1;
3690       Saved_Checks (Num_Saved_Checks) :=
3691         (Killed      => False,
3692          Entity      => Ent,
3693          Offset      => Ofs,
3694          Check_Type  => 'O',
3695          Target_Type => Empty);
3696
3697       if Debug_Flag_CC then
3698          w ("Make new entry, check number = ", Num_Saved_Checks);
3699          w ("  Entity = ", Int (Ent));
3700          Write_Str ("  Offset = ");
3701          pid (Ofs);
3702          w ("  Check_Type = O");
3703          w ("  Target_Type = Empty");
3704       end if;
3705
3706    --  If we get an exception, then something went wrong, probably because of
3707    --  an error in the structure of the tree due to an incorrect program. Or it
3708    --  may be a bug in the optimization circuit. In either case the safest
3709    --  thing is simply to set the check flag unconditionally.
3710
3711    exception
3712       when others =>
3713          Activate_Overflow_Check (N);
3714
3715          if Debug_Flag_CC then
3716             w ("  exception occurred, overflow flag set");
3717          end if;
3718
3719          return;
3720    end Enable_Overflow_Check;
3721
3722    ------------------------
3723    -- Enable_Range_Check --
3724    ------------------------
3725
3726    procedure Enable_Range_Check (N : Node_Id) is
3727       Chk  : Nat;
3728       OK   : Boolean;
3729       Ent  : Entity_Id;
3730       Ofs  : Uint;
3731       Ttyp : Entity_Id;
3732       P    : Node_Id;
3733
3734    begin
3735       --  Return if unchecked type conversion with range check killed. In this
3736       --  case we never set the flag (that's what Kill_Range_Check is about!)
3737
3738       if Nkind (N) = N_Unchecked_Type_Conversion
3739         and then Kill_Range_Check (N)
3740       then
3741          return;
3742       end if;
3743
3744       --  Check for various cases where we should suppress the range check
3745
3746       --  No check if range checks suppressed for type of node
3747
3748       if Present (Etype (N))
3749         and then Range_Checks_Suppressed (Etype (N))
3750       then
3751          return;
3752
3753       --  No check if node is an entity name, and range checks are suppressed
3754       --  for this entity, or for the type of this entity.
3755
3756       elsif Is_Entity_Name (N)
3757         and then (Range_Checks_Suppressed (Entity (N))
3758                     or else Range_Checks_Suppressed (Etype (Entity (N))))
3759       then
3760          return;
3761
3762       --  No checks if index of array, and index checks are suppressed for
3763       --  the array object or the type of the array.
3764
3765       elsif Nkind (Parent (N)) = N_Indexed_Component then
3766          declare
3767             Pref : constant Node_Id := Prefix (Parent (N));
3768          begin
3769             if Is_Entity_Name (Pref)
3770               and then Index_Checks_Suppressed (Entity (Pref))
3771             then
3772                return;
3773             elsif Index_Checks_Suppressed (Etype (Pref)) then
3774                return;
3775             end if;
3776          end;
3777       end if;
3778
3779       --  Debug trace output
3780
3781       if Debug_Flag_CC then
3782          w ("Enable_Range_Check for node ", Int (N));
3783          Write_Str ("  Source location = ");
3784          wl (Sloc (N));
3785          pg (Union_Id (N));
3786       end if;
3787
3788       --  If not in optimizing mode, set flag and we are done. We are also done
3789       --  (and just set the flag) if the type is not a discrete type, since it
3790       --  is not worth the effort to eliminate checks for other than discrete
3791       --  types. In addition, we take this same path if we have stored the
3792       --  maximum number of checks possible already (a very unlikely situation,
3793       --  but we do not want to blow up!)
3794
3795       if Optimization_Level = 0
3796         or else No (Etype (N))
3797         or else not Is_Discrete_Type (Etype (N))
3798         or else Num_Saved_Checks = Saved_Checks'Last
3799       then
3800          Activate_Range_Check (N);
3801
3802          if Debug_Flag_CC then
3803             w ("Optimization off");
3804          end if;
3805
3806          return;
3807       end if;
3808
3809       --  Otherwise find out the target type
3810
3811       P := Parent (N);
3812
3813       --  For assignment, use left side subtype
3814
3815       if Nkind (P) = N_Assignment_Statement
3816         and then Expression (P) = N
3817       then
3818          Ttyp := Etype (Name (P));
3819
3820       --  For indexed component, use subscript subtype
3821
3822       elsif Nkind (P) = N_Indexed_Component then
3823          declare
3824             Atyp : Entity_Id;
3825             Indx : Node_Id;
3826             Subs : Node_Id;
3827
3828          begin
3829             Atyp := Etype (Prefix (P));
3830
3831             if Is_Access_Type (Atyp) then
3832                Atyp := Designated_Type (Atyp);
3833
3834                --  If the prefix is an access to an unconstrained array,
3835                --  perform check unconditionally: it depends on the bounds of
3836                --  an object and we cannot currently recognize whether the test
3837                --  may be redundant.
3838
3839                if not Is_Constrained (Atyp) then
3840                   Activate_Range_Check (N);
3841                   return;
3842                end if;
3843
3844             --  Ditto if the prefix is an explicit dereference whose designated
3845             --  type is unconstrained.
3846
3847             elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3848               and then not Is_Constrained (Atyp)
3849             then
3850                Activate_Range_Check (N);
3851                return;
3852             end if;
3853
3854             Indx := First_Index (Atyp);
3855             Subs := First (Expressions (P));
3856             loop
3857                if Subs = N then
3858                   Ttyp := Etype (Indx);
3859                   exit;
3860                end if;
3861
3862                Next_Index (Indx);
3863                Next (Subs);
3864             end loop;
3865          end;
3866
3867       --  For now, ignore all other cases, they are not so interesting
3868
3869       else
3870          if Debug_Flag_CC then
3871             w ("  target type not found, flag set");
3872          end if;
3873
3874          Activate_Range_Check (N);
3875          return;
3876       end if;
3877
3878       --  Evaluate and check the expression
3879
3880       Find_Check
3881         (Expr        => N,
3882          Check_Type  => 'R',
3883          Target_Type => Ttyp,
3884          Entry_OK    => OK,
3885          Check_Num   => Chk,
3886          Ent         => Ent,
3887          Ofs         => Ofs);
3888
3889       if Debug_Flag_CC then
3890          w ("Called Find_Check");
3891          w ("Target_Typ = ", Int (Ttyp));
3892          w ("  OK = ", OK);
3893
3894          if OK then
3895             w ("  Check_Num = ", Chk);
3896             w ("  Ent       = ", Int (Ent));
3897             Write_Str ("  Ofs       = ");
3898             pid (Ofs);
3899          end if;
3900       end if;
3901
3902       --  If check is not of form to optimize, then set flag and we are done
3903
3904       if not OK then
3905          if Debug_Flag_CC then
3906             w ("  expression not of optimizable type, flag set");
3907          end if;
3908
3909          Activate_Range_Check (N);
3910          return;
3911       end if;
3912
3913       --  If check is already performed, then return without setting flag
3914
3915       if Chk /= 0 then
3916          if Debug_Flag_CC then
3917             w ("Check suppressed!");
3918          end if;
3919
3920          return;
3921       end if;
3922
3923       --  Here we will make a new entry for the new check
3924
3925       Activate_Range_Check (N);
3926       Num_Saved_Checks := Num_Saved_Checks + 1;
3927       Saved_Checks (Num_Saved_Checks) :=
3928         (Killed      => False,
3929          Entity      => Ent,
3930          Offset      => Ofs,
3931          Check_Type  => 'R',
3932          Target_Type => Ttyp);
3933
3934       if Debug_Flag_CC then
3935          w ("Make new entry, check number = ", Num_Saved_Checks);
3936          w ("  Entity = ", Int (Ent));
3937          Write_Str ("  Offset = ");
3938          pid (Ofs);
3939          w ("  Check_Type = R");
3940          w ("  Target_Type = ", Int (Ttyp));
3941          pg (Union_Id (Ttyp));
3942       end if;
3943
3944    --  If we get an exception, then something went wrong, probably because of
3945    --  an error in the structure of the tree due to an incorrect program. Or
3946    --  it may be a bug in the optimization circuit. In either case the safest
3947    --  thing is simply to set the check flag unconditionally.
3948
3949    exception
3950       when others =>
3951          Activate_Range_Check (N);
3952
3953          if Debug_Flag_CC then
3954             w ("  exception occurred, range flag set");
3955          end if;
3956
3957          return;
3958    end Enable_Range_Check;
3959
3960    ------------------
3961    -- Ensure_Valid --
3962    ------------------
3963
3964    procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3965       Typ : constant Entity_Id  := Etype (Expr);
3966
3967    begin
3968       --  Ignore call if we are not doing any validity checking
3969
3970       if not Validity_Checks_On then
3971          return;
3972
3973       --  Ignore call if range or validity checks suppressed on entity or type
3974
3975       elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3976          return;
3977
3978       --  No check required if expression is from the expander, we assume the
3979       --  expander will generate whatever checks are needed. Note that this is
3980       --  not just an optimization, it avoids infinite recursions!
3981
3982       --  Unchecked conversions must be checked, unless they are initialized
3983       --  scalar values, as in a component assignment in an init proc.
3984
3985       --  In addition, we force a check if Force_Validity_Checks is set
3986
3987       elsif not Comes_From_Source (Expr)
3988         and then not Force_Validity_Checks
3989         and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
3990                     or else Kill_Range_Check (Expr))
3991       then
3992          return;
3993
3994       --  No check required if expression is known to have valid value
3995
3996       elsif Expr_Known_Valid (Expr) then
3997          return;
3998
3999       --  Ignore case of enumeration with holes where the flag is set not to
4000       --  worry about holes, since no special validity check is needed
4001
4002       elsif Is_Enumeration_Type (Typ)
4003         and then Has_Non_Standard_Rep (Typ)
4004         and then Holes_OK
4005       then
4006          return;
4007
4008       --  No check required on the left-hand side of an assignment
4009
4010       elsif Nkind (Parent (Expr)) = N_Assignment_Statement
4011         and then Expr = Name (Parent (Expr))
4012       then
4013          return;
4014
4015       --  No check on a univeral real constant. The context will eventually
4016       --  convert it to a machine number for some target type, or report an
4017       --  illegality.
4018
4019       elsif Nkind (Expr) = N_Real_Literal
4020         and then Etype (Expr) = Universal_Real
4021       then
4022          return;
4023
4024       --  If the expression denotes a component of a packed boolean arrray,
4025       --  no possible check applies. We ignore the old ACATS chestnuts that
4026       --  involve Boolean range True..True.
4027
4028       --  Note: validity checks are generated for expressions that yield a
4029       --  scalar type, when it is possible to create a value that is outside of
4030       --  the type. If this is a one-bit boolean no such value exists. This is
4031       --  an optimization, and it also prevents compiler blowing up during the
4032       --  elaboration of improperly expanded packed array references.
4033
4034       elsif Nkind (Expr) = N_Indexed_Component
4035         and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
4036         and then Root_Type (Etype (Expr)) = Standard_Boolean
4037       then
4038          return;
4039
4040       --  An annoying special case. If this is an out parameter of a scalar
4041       --  type, then the value is not going to be accessed, therefore it is
4042       --  inappropriate to do any validity check at the call site.
4043
4044       else
4045          --  Only need to worry about scalar types
4046
4047          if Is_Scalar_Type (Typ) then
4048             declare
4049                P : Node_Id;
4050                N : Node_Id;
4051                E : Entity_Id;
4052                F : Entity_Id;
4053                A : Node_Id;
4054                L : List_Id;
4055
4056             begin
4057                --  Find actual argument (which may be a parameter association)
4058                --  and the parent of the actual argument (the call statement)
4059
4060                N := Expr;
4061                P := Parent (Expr);
4062
4063                if Nkind (P) = N_Parameter_Association then
4064                   N := P;
4065                   P := Parent (N);
4066                end if;
4067
4068                --  Only need to worry if we are argument of a procedure call
4069                --  since functions don't have out parameters. If this is an
4070                --  indirect or dispatching call, get signature from the
4071                --  subprogram type.
4072
4073                if Nkind (P) = N_Procedure_Call_Statement then
4074                   L := Parameter_Associations (P);
4075
4076                   if Is_Entity_Name (Name (P)) then
4077                      E := Entity (Name (P));
4078                   else
4079                      pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
4080                      E := Etype (Name (P));
4081                   end if;
4082
4083                   --  Only need to worry if there are indeed actuals, and if
4084                   --  this could be a procedure call, otherwise we cannot get a
4085                   --  match (either we are not an argument, or the mode of the
4086                   --  formal is not OUT). This test also filters out the
4087                   --  generic case.
4088
4089                   if Is_Non_Empty_List (L)
4090                     and then Is_Subprogram (E)
4091                   then
4092                      --  This is the loop through parameters, looking for an
4093                      --  OUT parameter for which we are the argument.
4094
4095                      F := First_Formal (E);
4096                      A := First (L);
4097                      while Present (F) loop
4098                         if Ekind (F) = E_Out_Parameter and then A = N then
4099                            return;
4100                         end if;
4101
4102                         Next_Formal (F);
4103                         Next (A);
4104                      end loop;
4105                   end if;
4106                end if;
4107             end;
4108          end if;
4109       end if;
4110
4111       --  If this is a boolean expression, only its elementary consituents need
4112       --  checking: if they are valid, a boolean or short-circuit operation
4113       --  with them will be valid as well.
4114
4115       if Base_Type (Typ) = Standard_Boolean
4116         and then
4117           (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
4118       then
4119          return;
4120       end if;
4121
4122       --  If we fall through, a validity check is required
4123
4124       Insert_Valid_Check (Expr);
4125
4126       if Is_Entity_Name (Expr)
4127         and then Safe_To_Capture_Value (Expr, Entity (Expr))
4128       then
4129          Set_Is_Known_Valid (Entity (Expr));
4130       end if;
4131    end Ensure_Valid;
4132
4133    ----------------------
4134    -- Expr_Known_Valid --
4135    ----------------------
4136
4137    function Expr_Known_Valid (Expr : Node_Id) return Boolean is
4138       Typ : constant Entity_Id := Etype (Expr);
4139
4140    begin
4141       --  Non-scalar types are always considered valid, since they never give
4142       --  rise to the issues of erroneous or bounded error behavior that are
4143       --  the concern. In formal reference manual terms the notion of validity
4144       --  only applies to scalar types. Note that even when packed arrays are
4145       --  represented using modular types, they are still arrays semantically,
4146       --  so they are also always valid (in particular, the unused bits can be
4147       --  random rubbish without affecting the validity of the array value).
4148
4149       if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
4150          return True;
4151
4152       --  If no validity checking, then everything is considered valid
4153
4154       elsif not Validity_Checks_On then
4155          return True;
4156
4157       --  Floating-point types are considered valid unless floating-point
4158       --  validity checks have been specifically turned on.
4159
4160       elsif Is_Floating_Point_Type (Typ)
4161         and then not Validity_Check_Floating_Point
4162       then
4163          return True;
4164
4165       --  If the expression is the value of an object that is known to be
4166       --  valid, then clearly the expression value itself is valid.
4167
4168       elsif Is_Entity_Name (Expr)
4169         and then Is_Known_Valid (Entity (Expr))
4170       then
4171          return True;
4172
4173       --  References to discriminants are always considered valid. The value
4174       --  of a discriminant gets checked when the object is built. Within the
4175       --  record, we consider it valid, and it is important to do so, since
4176       --  otherwise we can try to generate bogus validity checks which
4177       --  reference discriminants out of scope. Discriminants of concurrent
4178       --  types are excluded for the same reason.
4179
4180       elsif Is_Entity_Name (Expr)
4181         and then Denotes_Discriminant (Expr, Check_Concurrent => True)
4182       then
4183          return True;
4184
4185       --  If the type is one for which all values are known valid, then we are
4186       --  sure that the value is valid except in the slightly odd case where
4187       --  the expression is a reference to a variable whose size has been
4188       --  explicitly set to a value greater than the object size.
4189
4190       elsif Is_Known_Valid (Typ) then
4191          if Is_Entity_Name (Expr)
4192            and then Ekind (Entity (Expr)) = E_Variable
4193            and then Esize (Entity (Expr)) > Esize (Typ)
4194          then
4195             return False;
4196          else
4197             return True;
4198          end if;
4199
4200       --  Integer and character literals always have valid values, where
4201       --  appropriate these will be range checked in any case.
4202
4203       elsif Nkind (Expr) = N_Integer_Literal
4204               or else
4205             Nkind (Expr) = N_Character_Literal
4206       then
4207          return True;
4208
4209       --  If we have a type conversion or a qualification of a known valid
4210       --  value, then the result will always be valid.
4211
4212       elsif Nkind (Expr) = N_Type_Conversion
4213               or else
4214             Nkind (Expr) = N_Qualified_Expression
4215       then
4216          return Expr_Known_Valid (Expression (Expr));
4217
4218       --  The result of any operator is always considered valid, since we
4219       --  assume the necessary checks are done by the operator. For operators
4220       --  on floating-point operations, we must also check when the operation
4221       --  is the right-hand side of an assignment, or is an actual in a call.
4222
4223       elsif Nkind (Expr) in N_Op then
4224          if Is_Floating_Point_Type (Typ)
4225             and then Validity_Check_Floating_Point
4226             and then
4227               (Nkind (Parent (Expr)) = N_Assignment_Statement
4228                 or else Nkind (Parent (Expr)) = N_Function_Call
4229                 or else Nkind (Parent (Expr)) = N_Parameter_Association)
4230          then
4231             return False;
4232          else
4233             return True;
4234          end if;
4235
4236       --  The result of a membership test is always valid, since it is true or
4237       --  false, there are no other possibilities.
4238
4239       elsif Nkind (Expr) in N_Membership_Test then
4240          return True;
4241
4242       --  For all other cases, we do not know the expression is valid
4243
4244       else
4245          return False;
4246       end if;
4247    end Expr_Known_Valid;
4248
4249    ----------------
4250    -- Find_Check --
4251    ----------------
4252
4253    procedure Find_Check
4254      (Expr        : Node_Id;
4255       Check_Type  : Character;
4256       Target_Type : Entity_Id;
4257       Entry_OK    : out Boolean;
4258       Check_Num   : out Nat;
4259       Ent         : out Entity_Id;
4260       Ofs         : out Uint)
4261    is
4262       function Within_Range_Of
4263         (Target_Type : Entity_Id;
4264          Check_Type  : Entity_Id) return Boolean;
4265       --  Given a requirement for checking a range against Target_Type, and
4266       --  and a range Check_Type against which a check has already been made,
4267       --  determines if the check against check type is sufficient to ensure
4268       --  that no check against Target_Type is required.
4269
4270       ---------------------
4271       -- Within_Range_Of --
4272       ---------------------
4273
4274       function Within_Range_Of
4275         (Target_Type : Entity_Id;
4276          Check_Type  : Entity_Id) return Boolean
4277       is
4278       begin
4279          if Target_Type = Check_Type then
4280             return True;
4281
4282          else
4283             declare
4284                Tlo : constant Node_Id := Type_Low_Bound  (Target_Type);
4285                Thi : constant Node_Id := Type_High_Bound (Target_Type);
4286                Clo : constant Node_Id := Type_Low_Bound  (Check_Type);
4287                Chi : constant Node_Id := Type_High_Bound (Check_Type);
4288
4289             begin
4290                if (Tlo = Clo
4291                      or else (Compile_Time_Known_Value (Tlo)
4292                                 and then
4293                               Compile_Time_Known_Value (Clo)
4294                                 and then
4295                               Expr_Value (Clo) >= Expr_Value (Tlo)))
4296                  and then
4297                   (Thi = Chi
4298                      or else (Compile_Time_Known_Value (Thi)
4299                                 and then
4300                               Compile_Time_Known_Value (Chi)
4301                                 and then
4302                               Expr_Value (Chi) <= Expr_Value (Clo)))
4303                then
4304                   return True;
4305                else
4306                   return False;
4307                end if;
4308             end;
4309          end if;
4310       end Within_Range_Of;
4311
4312    --  Start of processing for Find_Check
4313
4314    begin
4315       --  Establish default, in case no entry is found
4316
4317       Check_Num := 0;
4318
4319       --  Case of expression is simple entity reference
4320
4321       if Is_Entity_Name (Expr) then
4322          Ent := Entity (Expr);
4323          Ofs := Uint_0;
4324
4325       --  Case of expression is entity + known constant
4326
4327       elsif Nkind (Expr) = N_Op_Add
4328         and then Compile_Time_Known_Value (Right_Opnd (Expr))
4329         and then Is_Entity_Name (Left_Opnd (Expr))
4330       then
4331          Ent := Entity (Left_Opnd (Expr));
4332          Ofs := Expr_Value (Right_Opnd (Expr));
4333
4334       --  Case of expression is entity - known constant
4335
4336       elsif Nkind (Expr) = N_Op_Subtract
4337         and then Compile_Time_Known_Value (Right_Opnd (Expr))
4338         and then Is_Entity_Name (Left_Opnd (Expr))
4339       then
4340          Ent := Entity (Left_Opnd (Expr));
4341          Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4342
4343       --  Any other expression is not of the right form
4344
4345       else
4346          Ent := Empty;
4347          Ofs := Uint_0;
4348          Entry_OK := False;
4349          return;
4350       end if;
4351
4352       --  Come here with expression of appropriate form, check if entity is an
4353       --  appropriate one for our purposes.
4354
4355       if (Ekind (Ent) = E_Variable
4356             or else Is_Constant_Object (Ent))
4357         and then not Is_Library_Level_Entity (Ent)
4358       then
4359          Entry_OK := True;
4360       else
4361          Entry_OK := False;
4362          return;
4363       end if;
4364
4365       --  See if there is matching check already
4366
4367       for J in reverse 1 .. Num_Saved_Checks loop
4368          declare
4369             SC : Saved_Check renames Saved_Checks (J);
4370
4371          begin
4372             if SC.Killed = False
4373               and then SC.Entity = Ent
4374               and then SC.Offset = Ofs
4375               and then SC.Check_Type = Check_Type
4376               and then Within_Range_Of (Target_Type, SC.Target_Type)
4377             then
4378                Check_Num := J;
4379                return;
4380             end if;
4381          end;
4382       end loop;
4383
4384       --  If we fall through entry was not found
4385
4386       return;
4387    end Find_Check;
4388
4389    ---------------------------------
4390    -- Generate_Discriminant_Check --
4391    ---------------------------------
4392
4393    --  Note: the code for this procedure is derived from the
4394    --  Emit_Discriminant_Check Routine in trans.c.
4395
4396    procedure Generate_Discriminant_Check (N : Node_Id) is
4397       Loc  : constant Source_Ptr := Sloc (N);
4398       Pref : constant Node_Id    := Prefix (N);
4399       Sel  : constant Node_Id    := Selector_Name (N);
4400
4401       Orig_Comp : constant Entity_Id :=
4402                     Original_Record_Component (Entity (Sel));
4403       --  The original component to be checked
4404
4405       Discr_Fct : constant Entity_Id :=
4406                     Discriminant_Checking_Func (Orig_Comp);
4407       --  The discriminant checking function
4408
4409       Discr : Entity_Id;
4410       --  One discriminant to be checked in the type
4411
4412       Real_Discr : Entity_Id;
4413       --  Actual discriminant in the call
4414
4415       Pref_Type : Entity_Id;
4416       --  Type of relevant prefix (ignoring private/access stuff)
4417
4418       Args : List_Id;
4419       --  List of arguments for function call
4420
4421       Formal : Entity_Id;
4422       --  Keep track of the formal corresponding to the actual we build for
4423       --  each discriminant, in order to be able to perform the necessary type
4424       --  conversions.
4425
4426       Scomp : Node_Id;
4427       --  Selected component reference for checking function argument
4428
4429    begin
4430       Pref_Type := Etype (Pref);
4431
4432       --  Force evaluation of the prefix, so that it does not get evaluated
4433       --  twice (once for the check, once for the actual reference). Such a
4434       --  double evaluation is always a potential source of inefficiency,
4435       --  and is functionally incorrect in the volatile case, or when the
4436       --  prefix may have side-effects. An entity or a component of an
4437       --  entity requires no evaluation.
4438
4439       if Is_Entity_Name (Pref) then
4440          if Treat_As_Volatile (Entity (Pref)) then
4441             Force_Evaluation (Pref, Name_Req => True);
4442          end if;
4443
4444       elsif Treat_As_Volatile (Etype (Pref)) then
4445             Force_Evaluation (Pref, Name_Req => True);
4446
4447       elsif Nkind (Pref) = N_Selected_Component
4448         and then Is_Entity_Name (Prefix (Pref))
4449       then
4450          null;
4451
4452       else
4453          Force_Evaluation (Pref, Name_Req => True);
4454       end if;
4455
4456       --  For a tagged type, use the scope of the original component to
4457       --  obtain the type, because ???
4458
4459       if Is_Tagged_Type (Scope (Orig_Comp)) then
4460          Pref_Type := Scope (Orig_Comp);
4461
4462       --  For an untagged derived type, use the discriminants of the parent
4463       --  which have been renamed in the derivation, possibly by a one-to-many
4464       --  discriminant constraint. For non-tagged type, initially get the Etype
4465       --  of the prefix
4466
4467       else
4468          if Is_Derived_Type (Pref_Type)
4469            and then Number_Discriminants (Pref_Type) /=
4470                     Number_Discriminants (Etype (Base_Type (Pref_Type)))
4471          then
4472             Pref_Type := Etype (Base_Type (Pref_Type));
4473          end if;
4474       end if;
4475
4476       --  We definitely should have a checking function, This routine should
4477       --  not be called if no discriminant checking function is present.
4478
4479       pragma Assert (Present (Discr_Fct));
4480
4481       --  Create the list of the actual parameters for the call. This list
4482       --  is the list of the discriminant fields of the record expression to
4483       --  be discriminant checked.
4484
4485       Args   := New_List;
4486       Formal := First_Formal (Discr_Fct);
4487       Discr  := First_Discriminant (Pref_Type);
4488       while Present (Discr) loop
4489
4490          --  If we have a corresponding discriminant field, and a parent
4491          --  subtype is present, then we want to use the corresponding
4492          --  discriminant since this is the one with the useful value.
4493
4494          if Present (Corresponding_Discriminant (Discr))
4495            and then Ekind (Pref_Type) = E_Record_Type
4496            and then Present (Parent_Subtype (Pref_Type))
4497          then
4498             Real_Discr := Corresponding_Discriminant (Discr);
4499          else
4500             Real_Discr := Discr;
4501          end if;
4502
4503          --  Construct the reference to the discriminant
4504
4505          Scomp :=
4506            Make_Selected_Component (Loc,
4507              Prefix =>
4508                Unchecked_Convert_To (Pref_Type,
4509                  Duplicate_Subexpr (Pref)),
4510              Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4511
4512          --  Manually analyze and resolve this selected component. We really
4513          --  want it just as it appears above, and do not want the expander
4514          --  playing discriminal games etc with this reference. Then we append
4515          --  the argument to the list we are gathering.
4516
4517          Set_Etype (Scomp, Etype (Real_Discr));
4518          Set_Analyzed (Scomp, True);
4519          Append_To (Args, Convert_To (Etype (Formal), Scomp));
4520
4521          Next_Formal_With_Extras (Formal);
4522          Next_Discriminant (Discr);
4523       end loop;
4524
4525       --  Now build and insert the call
4526
4527       Insert_Action (N,
4528         Make_Raise_Constraint_Error (Loc,
4529           Condition =>
4530             Make_Function_Call (Loc,
4531               Name => New_Occurrence_Of (Discr_Fct, Loc),
4532               Parameter_Associations => Args),
4533           Reason => CE_Discriminant_Check_Failed));
4534    end Generate_Discriminant_Check;
4535
4536    ---------------------------
4537    -- Generate_Index_Checks --
4538    ---------------------------
4539
4540    procedure Generate_Index_Checks (N : Node_Id) is
4541       Loc : constant Source_Ptr := Sloc (N);
4542       A   : constant Node_Id    := Prefix (N);
4543       Sub : Node_Id;
4544       Ind : Nat;
4545       Num : List_Id;
4546
4547    begin
4548       --  Ignore call if index checks suppressed for array object or type
4549
4550       if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4551         or else Index_Checks_Suppressed (Etype (A))
4552       then
4553          return;
4554       end if;
4555
4556       --  Generate the checks
4557
4558       Sub := First (Expressions (N));
4559       Ind := 1;
4560       while Present (Sub) loop
4561          if Do_Range_Check (Sub) then
4562             Set_Do_Range_Check (Sub, False);
4563
4564             --  Force evaluation except for the case of a simple name of a
4565             --  non-volatile entity.
4566
4567             if not Is_Entity_Name (Sub)
4568               or else Treat_As_Volatile (Entity (Sub))
4569             then
4570                Force_Evaluation (Sub);
4571             end if;
4572
4573             --  Generate a raise of constraint error with the appropriate
4574             --  reason and a condition of the form:
4575
4576             --    Base_Type(Sub) not in array'range (subscript)
4577
4578             --  Note that the reason we generate the conversion to the base
4579             --  type here is that we definitely want the range check to take
4580             --  place, even if it looks like the subtype is OK. Optimization
4581             --  considerations that allow us to omit the check have already
4582             --  been taken into account in the setting of the Do_Range_Check
4583             --  flag earlier on.
4584
4585             if Ind = 1 then
4586                Num := No_List;
4587             else
4588                Num :=  New_List (Make_Integer_Literal (Loc, Ind));
4589             end if;
4590
4591             Insert_Action (N,
4592               Make_Raise_Constraint_Error (Loc,
4593                 Condition =>
4594                   Make_Not_In (Loc,
4595                     Left_Opnd  =>
4596                       Convert_To (Base_Type (Etype (Sub)),
4597                         Duplicate_Subexpr_Move_Checks (Sub)),
4598                     Right_Opnd =>
4599                       Make_Attribute_Reference (Loc,
4600                         Prefix         =>
4601                           Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
4602                         Attribute_Name => Name_Range,
4603                         Expressions    => Num)),
4604                 Reason => CE_Index_Check_Failed));
4605          end if;
4606
4607          Ind := Ind + 1;
4608          Next (Sub);
4609       end loop;
4610    end Generate_Index_Checks;
4611
4612    --------------------------
4613    -- Generate_Range_Check --
4614    --------------------------
4615
4616    procedure Generate_Range_Check
4617      (N           : Node_Id;
4618       Target_Type : Entity_Id;
4619       Reason      : RT_Exception_Code)
4620    is
4621       Loc              : constant Source_Ptr := Sloc (N);
4622       Source_Type      : constant Entity_Id  := Etype (N);
4623       Source_Base_Type : constant Entity_Id  := Base_Type (Source_Type);
4624       Target_Base_Type : constant Entity_Id  := Base_Type (Target_Type);
4625
4626    begin
4627       --  First special case, if the source type is already within the range
4628       --  of the target type, then no check is needed (probably we should have
4629       --  stopped Do_Range_Check from being set in the first place, but better
4630       --  late than later in preventing junk code!
4631
4632       --  We do NOT apply this if the source node is a literal, since in this
4633       --  case the literal has already been labeled as having the subtype of
4634       --  the target.
4635
4636       if In_Subrange_Of (Source_Type, Target_Type)
4637         and then not
4638           (Nkind (N) = N_Integer_Literal
4639              or else
4640            Nkind (N) = N_Real_Literal
4641              or else
4642            Nkind (N) = N_Character_Literal
4643              or else
4644            (Is_Entity_Name (N)
4645               and then Ekind (Entity (N)) = E_Enumeration_Literal))
4646       then
4647          return;
4648       end if;
4649
4650       --  We need a check, so force evaluation of the node, so that it does
4651       --  not get evaluated twice (once for the check, once for the actual
4652       --  reference). Such a double evaluation is always a potential source
4653       --  of inefficiency, and is functionally incorrect in the volatile case.
4654
4655       if not Is_Entity_Name (N)
4656         or else Treat_As_Volatile (Entity (N))
4657       then
4658          Force_Evaluation (N);
4659       end if;
4660
4661       --  The easiest case is when Source_Base_Type and Target_Base_Type are
4662       --  the same since in this case we can simply do a direct check of the
4663       --  value of N against the bounds of Target_Type.
4664
4665       --    [constraint_error when N not in Target_Type]
4666
4667       --  Note: this is by far the most common case, for example all cases of
4668       --  checks on the RHS of assignments are in this category, but not all
4669       --  cases are like this. Notably conversions can involve two types.
4670
4671       if Source_Base_Type = Target_Base_Type then
4672          Insert_Action (N,
4673            Make_Raise_Constraint_Error (Loc,
4674              Condition =>
4675                Make_Not_In (Loc,
4676                  Left_Opnd  => Duplicate_Subexpr (N),
4677                  Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4678              Reason => Reason));
4679
4680       --  Next test for the case where the target type is within the bounds
4681       --  of the base type of the source type, since in this case we can
4682       --  simply convert these bounds to the base type of T to do the test.
4683
4684       --    [constraint_error when N not in
4685       --       Source_Base_Type (Target_Type'First)
4686       --         ..
4687       --       Source_Base_Type(Target_Type'Last))]
4688
4689       --  The conversions will always work and need no check
4690
4691       --  Unchecked_Convert_To is used instead of Convert_To to handle the case
4692       --  of converting from an enumeration value to an integer type, such as
4693       --  occurs for the case of generating a range check on Enum'Val(Exp)
4694       --  (which used to be handled by gigi). This is OK, since the conversion
4695       --  itself does not require a check.
4696
4697       elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4698          Insert_Action (N,
4699            Make_Raise_Constraint_Error (Loc,
4700              Condition =>
4701                Make_Not_In (Loc,
4702                  Left_Opnd  => Duplicate_Subexpr (N),
4703
4704                  Right_Opnd =>
4705                    Make_Range (Loc,
4706                      Low_Bound =>
4707                        Unchecked_Convert_To (Source_Base_Type,
4708                          Make_Attribute_Reference (Loc,
4709                            Prefix =>
4710                              New_Occurrence_Of (Target_Type, Loc),
4711                            Attribute_Name => Name_First)),
4712
4713                      High_Bound =>
4714                        Unchecked_Convert_To (Source_Base_Type,
4715                          Make_Attribute_Reference (Loc,
4716                            Prefix =>
4717                              New_Occurrence_Of (Target_Type, Loc),
4718                            Attribute_Name => Name_Last)))),
4719              Reason => Reason));
4720
4721       --  Note that at this stage we now that the Target_Base_Type is not in
4722       --  the range of the Source_Base_Type (since even the Target_Type itself
4723       --  is not in this range). It could still be the case that Source_Type is
4724       --  in range of the target base type since we have not checked that case.
4725
4726       --  If that is the case, we can freely convert the source to the target,
4727       --  and then test the target result against the bounds.
4728
4729       elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4730
4731          --  We make a temporary to hold the value of the converted value
4732          --  (converted to the base type), and then we will do the test against
4733          --  this temporary.
4734
4735          --     Tnn : constant Target_Base_Type := Target_Base_Type (N);
4736          --     [constraint_error when Tnn not in Target_Type]
4737
4738          --  Then the conversion itself is replaced by an occurrence of Tnn
4739
4740          declare
4741             Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4742
4743          begin
4744             Insert_Actions (N, New_List (
4745               Make_Object_Declaration (Loc,
4746                 Defining_Identifier => Tnn,
4747                 Object_Definition   =>
4748                   New_Occurrence_Of (Target_Base_Type, Loc),
4749                 Constant_Present    => True,
4750                 Expression          =>
4751                   Make_Type_Conversion (Loc,
4752                     Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4753                     Expression   => Duplicate_Subexpr (N))),
4754
4755               Make_Raise_Constraint_Error (Loc,
4756                 Condition =>
4757                   Make_Not_In (Loc,
4758                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
4759                     Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4760
4761                 Reason => Reason)));
4762
4763             Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4764
4765             --  Set the type of N, because the declaration for Tnn might not
4766             --  be analyzed yet, as is the case if N appears within a record
4767             --  declaration, as a discriminant constraint or expression.
4768
4769             Set_Etype (N, Target_Base_Type);
4770          end;
4771
4772       --  At this stage, we know that we have two scalar types, which are
4773       --  directly convertible, and where neither scalar type has a base
4774       --  range that is in the range of the other scalar type.
4775
4776       --  The only way this can happen is with a signed and unsigned type.
4777       --  So test for these two cases:
4778
4779       else
4780          --  Case of the source is unsigned and the target is signed
4781
4782          if Is_Unsigned_Type (Source_Base_Type)
4783            and then not Is_Unsigned_Type (Target_Base_Type)
4784          then
4785             --  If the source is unsigned and the target is signed, then we
4786             --  know that the source is not shorter than the target (otherwise
4787             --  the source base type would be in the target base type range).
4788
4789             --  In other words, the unsigned type is either the same size as
4790             --  the target, or it is larger. It cannot be smaller.
4791
4792             pragma Assert
4793               (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4794
4795             --  We only need to check the low bound if the low bound of the
4796             --  target type is non-negative. If the low bound of the target
4797             --  type is negative, then we know that we will fit fine.
4798
4799             --  If the high bound of the target type is negative, then we
4800             --  know we have a constraint error, since we can't possibly
4801             --  have a negative source.
4802
4803             --  With these two checks out of the way, we can do the check
4804             --  using the source type safely
4805
4806             --  This is definitely the most annoying case!
4807
4808             --    [constraint_error
4809             --       when (Target_Type'First >= 0
4810             --               and then
4811             --                 N < Source_Base_Type (Target_Type'First))
4812             --         or else Target_Type'Last < 0
4813             --         or else N > Source_Base_Type (Target_Type'Last)];
4814
4815             --  We turn off all checks since we know that the conversions
4816             --  will work fine, given the guards for negative values.
4817
4818             Insert_Action (N,
4819               Make_Raise_Constraint_Error (Loc,
4820                 Condition =>
4821                   Make_Or_Else (Loc,
4822                     Make_Or_Else (Loc,
4823                       Left_Opnd =>
4824                         Make_And_Then (Loc,
4825                           Left_Opnd => Make_Op_Ge (Loc,
4826                             Left_Opnd =>
4827                               Make_Attribute_Reference (Loc,
4828                                 Prefix =>
4829                                   New_Occurrence_Of (Target_Type, Loc),
4830                                 Attribute_Name => Name_First),
4831                             Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4832
4833                           Right_Opnd =>
4834                             Make_Op_Lt (Loc,
4835                               Left_Opnd => Duplicate_Subexpr (N),
4836                               Right_Opnd =>
4837                                 Convert_To (Source_Base_Type,
4838                                   Make_Attribute_Reference (Loc,
4839                                     Prefix =>
4840                                       New_Occurrence_Of (Target_Type, Loc),
4841                                     Attribute_Name => Name_First)))),
4842
4843                       Right_Opnd =>
4844                         Make_Op_Lt (Loc,
4845                           Left_Opnd =>
4846                             Make_Attribute_Reference (Loc,
4847                               Prefix => New_Occurrence_Of (Target_Type, Loc),
4848                               Attribute_Name => Name_Last),
4849                             Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4850
4851                     Right_Opnd =>
4852                       Make_Op_Gt (Loc,
4853                         Left_Opnd => Duplicate_Subexpr (N),
4854                         Right_Opnd =>
4855                           Convert_To (Source_Base_Type,
4856                             Make_Attribute_Reference (Loc,
4857                               Prefix => New_Occurrence_Of (Target_Type, Loc),
4858                               Attribute_Name => Name_Last)))),
4859
4860                 Reason => Reason),
4861               Suppress  => All_Checks);
4862
4863          --  Only remaining possibility is that the source is signed and
4864          --  the target is unsigned.
4865
4866          else
4867             pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4868                              and then Is_Unsigned_Type (Target_Base_Type));
4869
4870             --  If the source is signed and the target is unsigned, then we
4871             --  know that the target is not shorter than the source (otherwise
4872             --  the target base type would be in the source base type range).
4873
4874             --  In other words, the unsigned type is either the same size as
4875             --  the target, or it is larger. It cannot be smaller.
4876
4877             --  Clearly we have an error if the source value is negative since
4878             --  no unsigned type can have negative values. If the source type
4879             --  is non-negative, then the check can be done using the target
4880             --  type.
4881
4882             --    Tnn : constant Target_Base_Type (N) := Target_Type;
4883
4884             --    [constraint_error
4885             --       when N < 0 or else Tnn not in Target_Type];
4886
4887             --  We turn off all checks for the conversion of N to the target
4888             --  base type, since we generate the explicit check to ensure that
4889             --  the value is non-negative
4890
4891             declare
4892                Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
4893
4894             begin
4895                Insert_Actions (N, New_List (
4896                  Make_Object_Declaration (Loc,
4897                    Defining_Identifier => Tnn,
4898                    Object_Definition   =>
4899                      New_Occurrence_Of (Target_Base_Type, Loc),
4900                    Constant_Present    => True,
4901                    Expression          =>
4902                      Make_Unchecked_Type_Conversion (Loc,
4903                        Subtype_Mark =>
4904                          New_Occurrence_Of (Target_Base_Type, Loc),
4905                        Expression   => Duplicate_Subexpr (N))),
4906
4907                  Make_Raise_Constraint_Error (Loc,
4908                    Condition =>
4909                      Make_Or_Else (Loc,
4910                        Left_Opnd =>
4911                          Make_Op_Lt (Loc,
4912                            Left_Opnd  => Duplicate_Subexpr (N),
4913                            Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4914
4915                        Right_Opnd =>
4916                          Make_Not_In (Loc,
4917                            Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
4918                            Right_Opnd =>
4919                              New_Occurrence_Of (Target_Type, Loc))),
4920
4921                    Reason => Reason)),
4922                  Suppress => All_Checks);
4923
4924                --  Set the Etype explicitly, because Insert_Actions may have
4925                --  placed the declaration in the freeze list for an enclosing
4926                --  construct, and thus it is not analyzed yet.
4927
4928                Set_Etype (Tnn, Target_Base_Type);
4929                Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4930             end;
4931          end if;
4932       end if;
4933    end Generate_Range_Check;
4934
4935    ------------------
4936    -- Get_Check_Id --
4937    ------------------
4938
4939    function Get_Check_Id (N : Name_Id) return Check_Id is
4940    begin
4941       --  For standard check name, we can do a direct computation
4942
4943       if N in First_Check_Name .. Last_Check_Name then
4944          return Check_Id (N - (First_Check_Name - 1));
4945
4946       --  For non-standard names added by pragma Check_Name, search table
4947
4948       else
4949          for J in All_Checks + 1 .. Check_Names.Last loop
4950             if Check_Names.Table (J) = N then
4951                return J;
4952             end if;
4953          end loop;
4954       end if;
4955
4956       --  No matching name found
4957
4958       return No_Check_Id;
4959    end Get_Check_Id;
4960
4961    ---------------------
4962    -- Get_Discriminal --
4963    ---------------------
4964
4965    function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4966       Loc : constant Source_Ptr := Sloc (E);
4967       D   : Entity_Id;
4968       Sc  : Entity_Id;
4969
4970    begin
4971       --  The bound can be a bona fide parameter of a protected operation,
4972       --  rather than a prival encoded as an in-parameter.
4973
4974       if No (Discriminal_Link (Entity (Bound))) then
4975          return Bound;
4976       end if;
4977
4978       --  Climb the scope stack looking for an enclosing protected type. If
4979       --  we run out of scopes, return the bound itself.
4980
4981       Sc := Scope (E);
4982       while Present (Sc) loop
4983          if Sc = Standard_Standard then
4984             return Bound;
4985
4986          elsif Ekind (Sc) = E_Protected_Type then
4987             exit;
4988          end if;
4989
4990          Sc := Scope (Sc);
4991       end loop;
4992
4993       D := First_Discriminant (Sc);
4994       while Present (D) loop
4995          if Chars (D) = Chars (Bound) then
4996             return New_Occurrence_Of (Discriminal (D), Loc);
4997          end if;
4998
4999          Next_Discriminant (D);
5000       end loop;
5001
5002       return Bound;
5003    end Get_Discriminal;
5004
5005    ----------------------
5006    -- Get_Range_Checks --
5007    ----------------------
5008
5009    function Get_Range_Checks
5010      (Ck_Node    : Node_Id;
5011       Target_Typ : Entity_Id;
5012       Source_Typ : Entity_Id := Empty;
5013       Warn_Node  : Node_Id   := Empty) return Check_Result
5014    is
5015    begin
5016       return Selected_Range_Checks
5017         (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
5018    end Get_Range_Checks;
5019
5020    ------------------
5021    -- Guard_Access --
5022    ------------------
5023
5024    function Guard_Access
5025      (Cond    : Node_Id;
5026       Loc     : Source_Ptr;
5027       Ck_Node : Node_Id) return Node_Id
5028    is
5029    begin
5030       if Nkind (Cond) = N_Or_Else then
5031          Set_Paren_Count (Cond, 1);
5032       end if;
5033
5034       if Nkind (Ck_Node) = N_Allocator then
5035          return Cond;
5036       else
5037          return
5038            Make_And_Then (Loc,
5039              Left_Opnd =>
5040                Make_Op_Ne (Loc,
5041                  Left_Opnd  => Duplicate_Subexpr_No_Checks (Ck_Node),
5042                  Right_Opnd => Make_Null (Loc)),
5043              Right_Opnd => Cond);
5044       end if;
5045    end Guard_Access;
5046
5047    -----------------------------
5048    -- Index_Checks_Suppressed --
5049    -----------------------------
5050
5051    function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
5052    begin
5053       if Present (E) and then Checks_May_Be_Suppressed (E) then
5054          return Is_Check_Suppressed (E, Index_Check);
5055       else
5056          return Scope_Suppress (Index_Check);
5057       end if;
5058    end Index_Checks_Suppressed;
5059
5060    ----------------
5061    -- Initialize --
5062    ----------------
5063
5064    procedure Initialize is
5065    begin
5066       for J in Determine_Range_Cache_N'Range loop
5067          Determine_Range_Cache_N (J) := Empty;
5068       end loop;
5069
5070       Check_Names.Init;
5071
5072       for J in Int range 1 .. All_Checks loop
5073          Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
5074       end loop;
5075    end Initialize;
5076
5077    -------------------------
5078    -- Insert_Range_Checks --
5079    -------------------------
5080
5081    procedure Insert_Range_Checks
5082      (Checks       : Check_Result;
5083       Node         : Node_Id;
5084       Suppress_Typ : Entity_Id;
5085       Static_Sloc  : Source_Ptr := No_Location;
5086       Flag_Node    : Node_Id    := Empty;
5087       Do_Before    : Boolean    := False)
5088    is
5089       Internal_Flag_Node   : Node_Id    := Flag_Node;
5090       Internal_Static_Sloc : Source_Ptr := Static_Sloc;
5091
5092       Check_Node : Node_Id;
5093       Checks_On  : constant Boolean :=
5094                      (not Index_Checks_Suppressed (Suppress_Typ))
5095                        or else
5096                      (not Range_Checks_Suppressed (Suppress_Typ));
5097
5098    begin
5099       --  For now we just return if Checks_On is false, however this should be
5100       --  enhanced to check for an always True value in the condition and to
5101       --  generate a compilation warning???
5102
5103       if not Expander_Active or else not Checks_On then
5104          return;
5105       end if;
5106
5107       if Static_Sloc = No_Location then
5108          Internal_Static_Sloc := Sloc (Node);
5109       end if;
5110
5111       if No (Flag_Node) then
5112          Internal_Flag_Node := Node;
5113       end if;
5114
5115       for J in 1 .. 2 loop
5116          exit when No (Checks (J));
5117
5118          if Nkind (Checks (J)) = N_Raise_Constraint_Error
5119            and then Present (Condition (Checks (J)))
5120          then
5121             if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
5122                Check_Node := Checks (J);
5123                Mark_Rewrite_Insertion (Check_Node);
5124
5125                if Do_Before then
5126                   Insert_Before_And_Analyze (Node, Check_Node);
5127                else
5128                   Insert_After_And_Analyze (Node, Check_Node);
5129                end if;
5130
5131                Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
5132             end if;
5133
5134          else
5135             Check_Node :=
5136               Make_Raise_Constraint_Error (Internal_Static_Sloc,
5137                 Reason => CE_Range_Check_Failed);
5138             Mark_Rewrite_Insertion (Check_Node);
5139
5140             if Do_Before then
5141                Insert_Before_And_Analyze (Node, Check_Node);
5142             else
5143                Insert_After_And_Analyze (Node, Check_Node);
5144             end if;
5145          end if;
5146       end loop;
5147    end Insert_Range_Checks;
5148
5149    ------------------------
5150    -- Insert_Valid_Check --
5151    ------------------------
5152
5153    procedure Insert_Valid_Check (Expr : Node_Id) is
5154       Loc : constant Source_Ptr := Sloc (Expr);
5155       Exp : Node_Id;
5156
5157    begin
5158       --  Do not insert if checks off, or if not checking validity or
5159       --  if expression is known to be valid
5160
5161       if not Validity_Checks_On
5162         or else Range_Or_Validity_Checks_Suppressed (Expr)
5163         or else Expr_Known_Valid (Expr)
5164       then
5165          return;
5166       end if;
5167
5168       --  If we have a checked conversion, then validity check applies to
5169       --  the expression inside the conversion, not the result, since if
5170       --  the expression inside is valid, then so is the conversion result.
5171
5172       Exp := Expr;
5173       while Nkind (Exp) = N_Type_Conversion loop
5174          Exp := Expression (Exp);
5175       end loop;
5176
5177       --  We are about to insert the validity check for Exp. We save and
5178       --  reset the Do_Range_Check flag over this validity check, and then
5179       --  put it back for the final original reference (Exp may be rewritten).
5180
5181       declare
5182          DRC : constant Boolean := Do_Range_Check (Exp);
5183
5184       begin
5185          Set_Do_Range_Check (Exp, False);
5186
5187          --  Force evaluation to avoid multiple reads for atomic/volatile
5188
5189          if Is_Entity_Name (Exp)
5190            and then Is_Volatile (Entity (Exp))
5191          then
5192             Force_Evaluation (Exp, Name_Req => True);
5193          end if;
5194
5195          --  Insert the validity check. Note that we do this with validity
5196          --  checks turned off, to avoid recursion, we do not want validity
5197          --  checks on the validity checking code itself!
5198
5199          Insert_Action
5200            (Expr,
5201             Make_Raise_Constraint_Error (Loc,
5202               Condition =>
5203                 Make_Op_Not (Loc,
5204                   Right_Opnd =>
5205                     Make_Attribute_Reference (Loc,
5206                       Prefix =>
5207                         Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
5208                       Attribute_Name => Name_Valid)),
5209               Reason => CE_Invalid_Data),
5210             Suppress => Validity_Check);
5211
5212          --  If the expression is a a reference to an element of a bit-packed
5213          --  array, then it is rewritten as a renaming declaration. If the
5214          --  expression is an actual in a call, it has not been expanded,
5215          --  waiting for the proper point at which to do it. The same happens
5216          --  with renamings, so that we have to force the expansion now. This
5217          --  non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
5218          --  and exp_ch6.adb.
5219
5220          if Is_Entity_Name (Exp)
5221            and then Nkind (Parent (Entity (Exp))) =
5222                       N_Object_Renaming_Declaration
5223          then
5224             declare
5225                Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
5226             begin
5227                if Nkind (Old_Exp) = N_Indexed_Component
5228                  and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
5229                then
5230                   Expand_Packed_Element_Reference (Old_Exp);
5231                end if;
5232             end;
5233          end if;
5234
5235          --  Put back the Do_Range_Check flag on the resulting (possibly
5236          --  rewritten) expression.
5237
5238          --  Note: it might be thought that a validity check is not required
5239          --  when a range check is present, but that's not the case, because
5240          --  the back end is allowed to assume for the range check that the
5241          --  operand is within its declared range (an assumption that validity
5242          --  checking is all about NOT assuming!)
5243
5244          --  Note: no need to worry about Possible_Local_Raise here, it will
5245          --  already have been called if original node has Do_Range_Check set.
5246
5247          Set_Do_Range_Check (Exp, DRC);
5248       end;
5249    end Insert_Valid_Check;
5250
5251    ----------------------------------
5252    -- Install_Null_Excluding_Check --
5253    ----------------------------------
5254
5255    procedure Install_Null_Excluding_Check (N : Node_Id) is
5256       Loc : constant Source_Ptr := Sloc (N);
5257       Typ : constant Entity_Id  := Etype (N);
5258
5259       function Safe_To_Capture_In_Parameter_Value return Boolean;
5260       --  Determines if it is safe to capture Known_Non_Null status for an
5261       --  the entity referenced by node N. The caller ensures that N is indeed
5262       --  an entity name. It is safe to capture the non-null status for an IN
5263       --  parameter when the reference occurs within a declaration that is sure
5264       --  to be executed as part of the declarative region.
5265
5266       procedure Mark_Non_Null;
5267       --  After installation of check, if the node in question is an entity
5268       --  name, then mark this entity as non-null if possible.
5269
5270       function Safe_To_Capture_In_Parameter_Value return Boolean is
5271          E     : constant Entity_Id := Entity (N);
5272          S     : constant Entity_Id := Current_Scope;
5273          S_Par : Node_Id;
5274
5275       begin
5276          if Ekind (E) /= E_In_Parameter then
5277             return False;
5278          end if;
5279
5280          --  Two initial context checks. We must be inside a subprogram body
5281          --  with declarations and reference must not appear in nested scopes.
5282
5283          if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
5284            or else Scope (E) /= S
5285          then
5286             return False;
5287          end if;
5288
5289          S_Par := Parent (Parent (S));
5290
5291          if Nkind (S_Par) /= N_Subprogram_Body
5292            or else No (Declarations (S_Par))
5293          then
5294             return False;
5295          end if;
5296
5297          declare
5298             N_Decl : Node_Id;
5299             P      : Node_Id;
5300
5301          begin
5302             --  Retrieve the declaration node of N (if any). Note that N
5303             --  may be a part of a complex initialization expression.
5304
5305             P := Parent (N);
5306             N_Decl := Empty;
5307             while Present (P) loop
5308
5309                --  If we have a short circuit form, and we are within the right
5310                --  hand expression, we return false, since the right hand side
5311                --  is not guaranteed to be elaborated.
5312
5313                if Nkind (P) in N_Short_Circuit
5314                  and then N = Right_Opnd (P)
5315                then
5316                   return False;
5317                end if;
5318
5319                --  Similarly, if we are in a conditional expression and not
5320                --  part of the condition, then we return False, since neither
5321                --  the THEN or ELSE expressions will always be elaborated.
5322
5323                if Nkind (P) = N_Conditional_Expression
5324                  and then N /= First (Expressions (P))
5325                then
5326                   return False;
5327                end if;
5328
5329                --  If we are in a case eexpression, and not part of the
5330                --  expression, then we return False, since a particular
5331                --  branch may not always be elaborated
5332
5333                if Nkind (P) = N_Case_Expression
5334                  and then N /= Expression (P)
5335                then
5336                   return False;
5337                end if;
5338
5339                --  While traversing the parent chain, we find that N
5340                --  belongs to a statement, thus it may never appear in
5341                --  a declarative region.
5342
5343                if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5344                  or else Nkind (P) = N_Procedure_Call_Statement
5345                then
5346                   return False;
5347                end if;
5348
5349                --  If we are at a declaration, record it and exit
5350
5351                if Nkind (P) in N_Declaration
5352                  and then Nkind (P) not in N_Subprogram_Specification
5353                then
5354                   N_Decl := P;
5355                   exit;
5356                end if;
5357
5358                P := Parent (P);
5359             end loop;
5360
5361             if No (N_Decl) then
5362                return False;
5363             end if;
5364
5365             return List_Containing (N_Decl) = Declarations (S_Par);
5366          end;
5367       end Safe_To_Capture_In_Parameter_Value;
5368
5369       -------------------
5370       -- Mark_Non_Null --
5371       -------------------
5372
5373       procedure Mark_Non_Null is
5374       begin
5375          --  Only case of interest is if node N is an entity name
5376
5377          if Is_Entity_Name (N) then
5378
5379             --  For sure, we want to clear an indication that this is known to
5380             --  be null, since if we get past this check, it definitely is not!
5381
5382             Set_Is_Known_Null (Entity (N), False);
5383
5384             --  We can mark the entity as known to be non-null if either it is
5385             --  safe to capture the value, or in the case of an IN parameter,
5386             --  which is a constant, if the check we just installed is in the
5387             --  declarative region of the subprogram body. In this latter case,
5388             --  a check is decisive for the rest of the body if the expression
5389             --  is sure to be elaborated, since we know we have to elaborate
5390             --  all declarations before executing the body.
5391
5392             --  Couldn't this always be part of Safe_To_Capture_Value ???
5393
5394             if Safe_To_Capture_Value (N, Entity (N))
5395               or else Safe_To_Capture_In_Parameter_Value
5396             then
5397                Set_Is_Known_Non_Null (Entity (N));
5398             end if;
5399          end if;
5400       end Mark_Non_Null;
5401
5402    --  Start of processing for Install_Null_Excluding_Check
5403
5404    begin
5405       pragma Assert (Is_Access_Type (Typ));
5406
5407       --  No check inside a generic (why not???)
5408
5409       if Inside_A_Generic then
5410          return;
5411       end if;
5412
5413       --  No check needed if known to be non-null
5414
5415       if Known_Non_Null (N) then
5416          return;
5417       end if;
5418
5419       --  If known to be null, here is where we generate a compile time check
5420
5421       if Known_Null (N) then
5422
5423          --  Avoid generating warning message inside init procs
5424
5425          if not Inside_Init_Proc then
5426             Apply_Compile_Time_Constraint_Error
5427               (N,
5428                "null value not allowed here?",
5429                CE_Access_Check_Failed);
5430          else
5431             Insert_Action (N,
5432               Make_Raise_Constraint_Error (Loc,
5433                 Reason => CE_Access_Check_Failed));
5434          end if;
5435
5436          Mark_Non_Null;
5437          return;
5438       end if;
5439
5440       --  If entity is never assigned, for sure a warning is appropriate
5441
5442       if Is_Entity_Name (N) then
5443          Check_Unset_Reference (N);
5444       end if;
5445
5446       --  No check needed if checks are suppressed on the range. Note that we
5447       --  don't set Is_Known_Non_Null in this case (we could legitimately do
5448       --  so, since the program is erroneous, but we don't like to casually
5449       --  propagate such conclusions from erroneosity).
5450
5451       if Access_Checks_Suppressed (Typ) then
5452          return;
5453       end if;
5454
5455       --  No check needed for access to concurrent record types generated by
5456       --  the expander. This is not just an optimization (though it does indeed
5457       --  remove junk checks). It also avoids generation of junk warnings.
5458
5459       if Nkind (N) in N_Has_Chars
5460         and then Chars (N) = Name_uObject
5461         and then Is_Concurrent_Record_Type
5462                    (Directly_Designated_Type (Etype (N)))
5463       then
5464          return;
5465       end if;
5466
5467       --  Otherwise install access check
5468
5469       Insert_Action (N,
5470         Make_Raise_Constraint_Error (Loc,
5471           Condition =>
5472             Make_Op_Eq (Loc,
5473               Left_Opnd  => Duplicate_Subexpr_Move_Checks (N),
5474               Right_Opnd => Make_Null (Loc)),
5475           Reason => CE_Access_Check_Failed));
5476
5477       Mark_Non_Null;
5478    end Install_Null_Excluding_Check;
5479
5480    --------------------------
5481    -- Install_Static_Check --
5482    --------------------------
5483
5484    procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5485       Stat : constant Boolean   := Is_Static_Expression (R_Cno);
5486       Typ  : constant Entity_Id := Etype (R_Cno);
5487
5488    begin
5489       Rewrite (R_Cno,
5490         Make_Raise_Constraint_Error (Loc,
5491           Reason => CE_Range_Check_Failed));
5492       Set_Analyzed (R_Cno);
5493       Set_Etype (R_Cno, Typ);
5494       Set_Raises_Constraint_Error (R_Cno);
5495       Set_Is_Static_Expression (R_Cno, Stat);
5496
5497       --  Now deal with possible local raise handling
5498
5499       Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
5500    end Install_Static_Check;
5501
5502    ---------------------
5503    -- Kill_All_Checks --
5504    ---------------------
5505
5506    procedure Kill_All_Checks is
5507    begin
5508       if Debug_Flag_CC then
5509          w ("Kill_All_Checks");
5510       end if;
5511
5512       --  We reset the number of saved checks to zero, and also modify all
5513       --  stack entries for statement ranges to indicate that the number of
5514       --  checks at each level is now zero.
5515
5516       Num_Saved_Checks := 0;
5517
5518       --  Note: the Int'Min here avoids any possibility of J being out of
5519       --  range when called from e.g. Conditional_Statements_Begin.
5520
5521       for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
5522          Saved_Checks_Stack (J) := 0;
5523       end loop;
5524    end Kill_All_Checks;
5525
5526    -----------------
5527    -- Kill_Checks --
5528    -----------------
5529
5530    procedure Kill_Checks (V : Entity_Id) is
5531    begin
5532       if Debug_Flag_CC then
5533          w ("Kill_Checks for entity", Int (V));
5534       end if;
5535
5536       for J in 1 .. Num_Saved_Checks loop
5537          if Saved_Checks (J).Entity = V then
5538             if Debug_Flag_CC then
5539                w ("   Checks killed for saved check ", J);
5540             end if;
5541
5542             Saved_Checks (J).Killed := True;
5543          end if;
5544       end loop;
5545    end Kill_Checks;
5546
5547    ------------------------------
5548    -- Length_Checks_Suppressed --
5549    ------------------------------
5550
5551    function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5552    begin
5553       if Present (E) and then Checks_May_Be_Suppressed (E) then
5554          return Is_Check_Suppressed (E, Length_Check);
5555       else
5556          return Scope_Suppress (Length_Check);
5557       end if;
5558    end Length_Checks_Suppressed;
5559
5560    --------------------------------
5561    -- Overflow_Checks_Suppressed --
5562    --------------------------------
5563
5564    function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5565    begin
5566       if Present (E) and then Checks_May_Be_Suppressed (E) then
5567          return Is_Check_Suppressed (E, Overflow_Check);
5568       else
5569          return Scope_Suppress (Overflow_Check);
5570       end if;
5571    end Overflow_Checks_Suppressed;
5572
5573    -----------------------------
5574    -- Range_Checks_Suppressed --
5575    -----------------------------
5576
5577    function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5578    begin
5579       if Present (E) then
5580
5581          --  Note: for now we always suppress range checks on Vax float types,
5582          --  since Gigi does not know how to generate these checks.
5583
5584          if Vax_Float (E) then
5585             return True;
5586          elsif Kill_Range_Checks (E) then
5587             return True;
5588          elsif Checks_May_Be_Suppressed (E) then
5589             return Is_Check_Suppressed (E, Range_Check);
5590          end if;
5591       end if;
5592
5593       return Scope_Suppress (Range_Check);
5594    end Range_Checks_Suppressed;
5595
5596    -----------------------------------------
5597    -- Range_Or_Validity_Checks_Suppressed --
5598    -----------------------------------------
5599
5600    --  Note: the coding would be simpler here if we simply made appropriate
5601    --  calls to Range/Validity_Checks_Suppressed, but that would result in
5602    --  duplicated checks which we prefer to avoid.
5603
5604    function Range_Or_Validity_Checks_Suppressed
5605      (Expr : Node_Id) return Boolean
5606    is
5607    begin
5608       --  Immediate return if scope checks suppressed for either check
5609
5610       if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5611          return True;
5612       end if;
5613
5614       --  If no expression, that's odd, decide that checks are suppressed,
5615       --  since we don't want anyone trying to do checks in this case, which
5616       --  is most likely the result of some other error.
5617
5618       if No (Expr) then
5619          return True;
5620       end if;
5621
5622       --  Expression is present, so perform suppress checks on type
5623
5624       declare
5625          Typ : constant Entity_Id := Etype (Expr);
5626       begin
5627          if Vax_Float (Typ) then
5628             return True;
5629          elsif Checks_May_Be_Suppressed (Typ)
5630            and then (Is_Check_Suppressed (Typ, Range_Check)
5631                        or else
5632                      Is_Check_Suppressed (Typ, Validity_Check))
5633          then
5634             return True;
5635          end if;
5636       end;
5637
5638       --  If expression is an entity name, perform checks on this entity
5639
5640       if Is_Entity_Name (Expr) then
5641          declare
5642             Ent : constant Entity_Id := Entity (Expr);
5643          begin
5644             if Checks_May_Be_Suppressed (Ent) then
5645                return Is_Check_Suppressed (Ent, Range_Check)
5646                  or else Is_Check_Suppressed (Ent, Validity_Check);
5647             end if;
5648          end;
5649       end if;
5650
5651       --  If we fall through, no checks suppressed
5652
5653       return False;
5654    end Range_Or_Validity_Checks_Suppressed;
5655
5656    -------------------
5657    -- Remove_Checks --
5658    -------------------
5659
5660    procedure Remove_Checks (Expr : Node_Id) is
5661       function Process (N : Node_Id) return Traverse_Result;
5662       --  Process a single node during the traversal
5663
5664       procedure Traverse is new Traverse_Proc (Process);
5665       --  The traversal procedure itself
5666
5667       -------------
5668       -- Process --
5669       -------------
5670
5671       function Process (N : Node_Id) return Traverse_Result is
5672       begin
5673          if Nkind (N) not in N_Subexpr then
5674             return Skip;
5675          end if;
5676
5677          Set_Do_Range_Check (N, False);
5678
5679          case Nkind (N) is
5680             when N_And_Then =>
5681                Traverse (Left_Opnd (N));
5682                return Skip;
5683
5684             when N_Attribute_Reference =>
5685                Set_Do_Overflow_Check (N, False);
5686
5687             when N_Function_Call =>
5688                Set_Do_Tag_Check (N, False);
5689
5690             when N_Op =>
5691                Set_Do_Overflow_Check (N, False);
5692
5693                case Nkind (N) is
5694                   when N_Op_Divide =>
5695                      Set_Do_Division_Check (N, False);
5696
5697                   when N_Op_And =>
5698                      Set_Do_Length_Check (N, False);
5699
5700                   when N_Op_Mod =>
5701                      Set_Do_Division_Check (N, False);
5702
5703                   when N_Op_Or =>
5704                      Set_Do_Length_Check (N, False);
5705
5706                   when N_Op_Rem =>
5707                      Set_Do_Division_Check (N, False);
5708
5709                   when N_Op_Xor =>
5710                      Set_Do_Length_Check (N, False);
5711
5712                   when others =>
5713                      null;
5714                end case;
5715
5716             when N_Or_Else =>
5717                Traverse (Left_Opnd (N));
5718                return Skip;
5719
5720             when N_Selected_Component =>
5721                Set_Do_Discriminant_Check (N, False);
5722
5723             when N_Type_Conversion =>
5724                Set_Do_Length_Check   (N, False);
5725                Set_Do_Tag_Check      (N, False);
5726                Set_Do_Overflow_Check (N, False);
5727
5728             when others =>
5729                null;
5730          end case;
5731
5732          return OK;
5733       end Process;
5734
5735    --  Start of processing for Remove_Checks
5736
5737    begin
5738       Traverse (Expr);
5739    end Remove_Checks;
5740
5741    ----------------------------
5742    -- Selected_Length_Checks --
5743    ----------------------------
5744
5745    function Selected_Length_Checks
5746      (Ck_Node    : Node_Id;
5747       Target_Typ : Entity_Id;
5748       Source_Typ : Entity_Id;
5749       Warn_Node  : Node_Id) return Check_Result
5750    is
5751       Loc         : constant Source_Ptr := Sloc (Ck_Node);
5752       S_Typ       : Entity_Id;
5753       T_Typ       : Entity_Id;
5754       Expr_Actual : Node_Id;
5755       Exptyp      : Entity_Id;
5756       Cond        : Node_Id := Empty;
5757       Do_Access   : Boolean := False;
5758       Wnode       : Node_Id := Warn_Node;
5759       Ret_Result  : Check_Result := (Empty, Empty);
5760       Num_Checks  : Natural := 0;
5761
5762       procedure Add_Check (N : Node_Id);
5763       --  Adds the action given to Ret_Result if N is non-Empty
5764
5765       function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5766       function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5767       --  Comments required ???
5768
5769       function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5770       --  True for equal literals and for nodes that denote the same constant
5771       --  entity, even if its value is not a static constant. This includes the
5772       --  case of a discriminal reference within an init proc. Removes some
5773       --  obviously superfluous checks.
5774
5775       function Length_E_Cond
5776         (Exptyp : Entity_Id;
5777          Typ    : Entity_Id;
5778          Indx   : Nat) return Node_Id;
5779       --  Returns expression to compute:
5780       --    Typ'Length /= Exptyp'Length
5781
5782       function Length_N_Cond
5783         (Expr : Node_Id;
5784          Typ  : Entity_Id;
5785          Indx : Nat) return Node_Id;
5786       --  Returns expression to compute:
5787       --    Typ'Length /= Expr'Length
5788
5789       ---------------
5790       -- Add_Check --
5791       ---------------
5792
5793       procedure Add_Check (N : Node_Id) is
5794       begin
5795          if Present (N) then
5796
5797             --  For now, ignore attempt to place more than 2 checks ???
5798
5799             if Num_Checks = 2 then
5800                return;
5801             end if;
5802
5803             pragma Assert (Num_Checks <= 1);
5804             Num_Checks := Num_Checks + 1;
5805             Ret_Result (Num_Checks) := N;
5806          end if;
5807       end Add_Check;
5808
5809       ------------------
5810       -- Get_E_Length --
5811       ------------------
5812
5813       function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5814          SE : constant Entity_Id := Scope (E);
5815          N  : Node_Id;
5816          E1 : Entity_Id := E;
5817
5818       begin
5819          if Ekind (Scope (E)) = E_Record_Type
5820            and then Has_Discriminants (Scope (E))
5821          then
5822             N := Build_Discriminal_Subtype_Of_Component (E);
5823
5824             if Present (N) then
5825                Insert_Action (Ck_Node, N);
5826                E1 := Defining_Identifier (N);
5827             end if;
5828          end if;
5829
5830          if Ekind (E1) = E_String_Literal_Subtype then
5831             return
5832               Make_Integer_Literal (Loc,
5833                 Intval => String_Literal_Length (E1));
5834
5835          elsif SE /= Standard_Standard
5836            and then Ekind (Scope (SE)) = E_Protected_Type
5837            and then Has_Discriminants (Scope (SE))
5838            and then Has_Completion (Scope (SE))
5839            and then not Inside_Init_Proc
5840          then
5841             --  If the type whose length is needed is a private component
5842             --  constrained by a discriminant, we must expand the 'Length
5843             --  attribute into an explicit computation, using the discriminal
5844             --  of the current protected operation. This is because the actual
5845             --  type of the prival is constructed after the protected opera-
5846             --  tion has been fully expanded.
5847
5848             declare
5849                Indx_Type : Node_Id;
5850                Lo        : Node_Id;
5851                Hi        : Node_Id;
5852                Do_Expand : Boolean := False;
5853
5854             begin
5855                Indx_Type := First_Index (E);
5856
5857                for J in 1 .. Indx - 1 loop
5858                   Next_Index (Indx_Type);
5859                end loop;
5860
5861                Get_Index_Bounds (Indx_Type, Lo, Hi);
5862
5863                if Nkind (Lo) = N_Identifier
5864                  and then Ekind (Entity (Lo)) = E_In_Parameter
5865                then
5866                   Lo := Get_Discriminal (E, Lo);
5867                   Do_Expand := True;
5868                end if;
5869
5870                if Nkind (Hi) = N_Identifier
5871                  and then Ekind (Entity (Hi)) = E_In_Parameter
5872                then
5873                   Hi := Get_Discriminal (E, Hi);
5874                   Do_Expand := True;
5875                end if;
5876
5877                if Do_Expand then
5878                   if not Is_Entity_Name (Lo) then
5879                      Lo := Duplicate_Subexpr_No_Checks (Lo);
5880                   end if;
5881
5882                   if not Is_Entity_Name (Hi) then
5883                      Lo := Duplicate_Subexpr_No_Checks (Hi);
5884                   end if;
5885
5886                   N :=
5887                     Make_Op_Add (Loc,
5888                       Left_Opnd =>
5889                         Make_Op_Subtract (Loc,
5890                           Left_Opnd  => Hi,
5891                           Right_Opnd => Lo),
5892
5893                       Right_Opnd => Make_Integer_Literal (Loc, 1));
5894                   return N;
5895
5896                else
5897                   N :=
5898                     Make_Attribute_Reference (Loc,
5899                       Attribute_Name => Name_Length,
5900                       Prefix =>
5901                         New_Occurrence_Of (E1, Loc));
5902
5903                   if Indx > 1 then
5904                      Set_Expressions (N, New_List (
5905                        Make_Integer_Literal (Loc, Indx)));
5906                   end if;
5907
5908                   return N;
5909                end if;
5910             end;
5911
5912          else
5913             N :=
5914               Make_Attribute_Reference (Loc,
5915                 Attribute_Name => Name_Length,
5916                 Prefix =>
5917                   New_Occurrence_Of (E1, Loc));
5918
5919             if Indx > 1 then
5920                Set_Expressions (N, New_List (
5921                  Make_Integer_Literal (Loc, Indx)));
5922             end if;
5923
5924             return N;
5925          end if;
5926       end Get_E_Length;
5927
5928       ------------------
5929       -- Get_N_Length --
5930       ------------------
5931
5932       function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5933       begin
5934          return
5935            Make_Attribute_Reference (Loc,
5936              Attribute_Name => Name_Length,
5937              Prefix =>
5938                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5939              Expressions => New_List (
5940                Make_Integer_Literal (Loc, Indx)));
5941       end Get_N_Length;
5942
5943       -------------------
5944       -- Length_E_Cond --
5945       -------------------
5946
5947       function Length_E_Cond
5948         (Exptyp : Entity_Id;
5949          Typ    : Entity_Id;
5950          Indx   : Nat) return Node_Id
5951       is
5952       begin
5953          return
5954            Make_Op_Ne (Loc,
5955              Left_Opnd  => Get_E_Length (Typ, Indx),
5956              Right_Opnd => Get_E_Length (Exptyp, Indx));
5957       end Length_E_Cond;
5958
5959       -------------------
5960       -- Length_N_Cond --
5961       -------------------
5962
5963       function Length_N_Cond
5964         (Expr : Node_Id;
5965          Typ  : Entity_Id;
5966          Indx : Nat) return Node_Id
5967       is
5968       begin
5969          return
5970            Make_Op_Ne (Loc,
5971              Left_Opnd  => Get_E_Length (Typ, Indx),
5972              Right_Opnd => Get_N_Length (Expr, Indx));
5973       end Length_N_Cond;
5974
5975       -----------------
5976       -- Same_Bounds --
5977       -----------------
5978
5979       function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5980       begin
5981          return
5982            (Nkind (L) = N_Integer_Literal
5983              and then Nkind (R) = N_Integer_Literal
5984              and then Intval (L) = Intval (R))
5985
5986           or else
5987             (Is_Entity_Name (L)
5988               and then Ekind (Entity (L)) = E_Constant
5989               and then ((Is_Entity_Name (R)
5990                          and then Entity (L) = Entity (R))
5991                         or else
5992                        (Nkind (R) = N_Type_Conversion
5993                          and then Is_Entity_Name (Expression (R))
5994                          and then Entity (L) = Entity (Expression (R)))))
5995
5996           or else
5997             (Is_Entity_Name (R)
5998               and then Ekind (Entity (R)) = E_Constant
5999               and then Nkind (L) = N_Type_Conversion
6000               and then Is_Entity_Name (Expression (L))
6001               and then Entity (R) = Entity (Expression (L)))
6002
6003          or else
6004             (Is_Entity_Name (L)
6005               and then Is_Entity_Name (R)
6006               and then Entity (L) = Entity (R)
6007               and then Ekind (Entity (L)) = E_In_Parameter
6008               and then Inside_Init_Proc);
6009       end Same_Bounds;
6010
6011    --  Start of processing for Selected_Length_Checks
6012
6013    begin
6014       if not Expander_Active then
6015          return Ret_Result;
6016       end if;
6017
6018       if Target_Typ = Any_Type
6019         or else Target_Typ = Any_Composite
6020         or else Raises_Constraint_Error (Ck_Node)
6021       then
6022          return Ret_Result;
6023       end if;
6024
6025       if No (Wnode) then
6026          Wnode := Ck_Node;
6027       end if;
6028
6029       T_Typ := Target_Typ;
6030
6031       if No (Source_Typ) then
6032          S_Typ := Etype (Ck_Node);
6033       else
6034          S_Typ := Source_Typ;
6035       end if;
6036
6037       if S_Typ = Any_Type or else S_Typ = Any_Composite then
6038          return Ret_Result;
6039       end if;
6040
6041       if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6042          S_Typ := Designated_Type (S_Typ);
6043          T_Typ := Designated_Type (T_Typ);
6044          Do_Access := True;
6045
6046          --  A simple optimization for the null case
6047
6048          if Known_Null (Ck_Node) then
6049             return Ret_Result;
6050          end if;
6051       end if;
6052
6053       if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6054          if Is_Constrained (T_Typ) then
6055
6056             --  The checking code to be generated will freeze the
6057             --  corresponding array type. However, we must freeze the
6058             --  type now, so that the freeze node does not appear within
6059             --  the generated condional expression, but ahead of it.
6060
6061             Freeze_Before (Ck_Node, T_Typ);
6062
6063             Expr_Actual := Get_Referenced_Object (Ck_Node);
6064             Exptyp      := Get_Actual_Subtype (Ck_Node);
6065
6066             if Is_Access_Type (Exptyp) then
6067                Exptyp := Designated_Type (Exptyp);
6068             end if;
6069
6070             --  String_Literal case. This needs to be handled specially be-
6071             --  cause no index types are available for string literals. The
6072             --  condition is simply:
6073
6074             --    T_Typ'Length = string-literal-length
6075
6076             if Nkind (Expr_Actual) = N_String_Literal
6077               and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
6078             then
6079                Cond :=
6080                  Make_Op_Ne (Loc,
6081                    Left_Opnd  => Get_E_Length (T_Typ, 1),
6082                    Right_Opnd =>
6083                      Make_Integer_Literal (Loc,
6084                        Intval =>
6085                          String_Literal_Length (Etype (Expr_Actual))));
6086
6087             --  General array case. Here we have a usable actual subtype for
6088             --  the expression, and the condition is built from the two types
6089             --  (Do_Length):
6090
6091             --     T_Typ'Length     /= Exptyp'Length     or else
6092             --     T_Typ'Length (2) /= Exptyp'Length (2) or else
6093             --     T_Typ'Length (3) /= Exptyp'Length (3) or else
6094             --     ...
6095
6096             elsif Is_Constrained (Exptyp) then
6097                declare
6098                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6099
6100                   L_Index  : Node_Id;
6101                   R_Index  : Node_Id;
6102                   L_Low    : Node_Id;
6103                   L_High   : Node_Id;
6104                   R_Low    : Node_Id;
6105                   R_High   : Node_Id;
6106                   L_Length : Uint;
6107                   R_Length : Uint;
6108                   Ref_Node : Node_Id;
6109
6110                begin
6111                   --  At the library level, we need to ensure that the type of
6112                   --  the object is elaborated before the check itself is
6113                   --  emitted. This is only done if the object is in the
6114                   --  current compilation unit, otherwise the type is frozen
6115                   --  and elaborated in its unit.
6116
6117                   if Is_Itype (Exptyp)
6118                     and then
6119                       Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
6120                     and then
6121                       not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
6122                     and then In_Open_Scopes (Scope (Exptyp))
6123                   then
6124                      Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
6125                      Set_Itype (Ref_Node, Exptyp);
6126                      Insert_Action (Ck_Node, Ref_Node);
6127                   end if;
6128
6129                   L_Index := First_Index (T_Typ);
6130                   R_Index := First_Index (Exptyp);
6131
6132                   for Indx in 1 .. Ndims loop
6133                      if not (Nkind (L_Index) = N_Raise_Constraint_Error
6134                                or else
6135                              Nkind (R_Index) = N_Raise_Constraint_Error)
6136                      then
6137                         Get_Index_Bounds (L_Index, L_Low, L_High);
6138                         Get_Index_Bounds (R_Index, R_Low, R_High);
6139
6140                         --  Deal with compile time length check. Note that we
6141                         --  skip this in the access case, because the access
6142                         --  value may be null, so we cannot know statically.
6143
6144                         if not Do_Access
6145                           and then Compile_Time_Known_Value (L_Low)
6146                           and then Compile_Time_Known_Value (L_High)
6147                           and then Compile_Time_Known_Value (R_Low)
6148                           and then Compile_Time_Known_Value (R_High)
6149                         then
6150                            if Expr_Value (L_High) >= Expr_Value (L_Low) then
6151                               L_Length := Expr_Value (L_High) -
6152                                           Expr_Value (L_Low) + 1;
6153                            else
6154                               L_Length := UI_From_Int (0);
6155                            end if;
6156
6157                            if Expr_Value (R_High) >= Expr_Value (R_Low) then
6158                               R_Length := Expr_Value (R_High) -
6159                                           Expr_Value (R_Low) + 1;
6160                            else
6161                               R_Length := UI_From_Int (0);
6162                            end if;
6163
6164                            if L_Length > R_Length then
6165                               Add_Check
6166                                 (Compile_Time_Constraint_Error
6167                                   (Wnode, "too few elements for}?", T_Typ));
6168
6169                            elsif  L_Length < R_Length then
6170                               Add_Check
6171                                 (Compile_Time_Constraint_Error
6172                                   (Wnode, "too many elements for}?", T_Typ));
6173                            end if;
6174
6175                         --  The comparison for an individual index subtype
6176                         --  is omitted if the corresponding index subtypes
6177                         --  statically match, since the result is known to
6178                         --  be true. Note that this test is worth while even
6179                         --  though we do static evaluation, because non-static
6180                         --  subtypes can statically match.
6181
6182                         elsif not
6183                           Subtypes_Statically_Match
6184                             (Etype (L_Index), Etype (R_Index))
6185
6186                           and then not
6187                             (Same_Bounds (L_Low, R_Low)
6188                               and then Same_Bounds (L_High, R_High))
6189                         then
6190                            Evolve_Or_Else
6191                              (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
6192                         end if;
6193
6194                         Next (L_Index);
6195                         Next (R_Index);
6196                      end if;
6197                   end loop;
6198                end;
6199
6200             --  Handle cases where we do not get a usable actual subtype that
6201             --  is constrained. This happens for example in the function call
6202             --  and explicit dereference cases. In these cases, we have to get
6203             --  the length or range from the expression itself, making sure we
6204             --  do not evaluate it more than once.
6205
6206             --  Here Ck_Node is the original expression, or more properly the
6207             --  result of applying Duplicate_Expr to the original tree, forcing
6208             --  the result to be a name.
6209
6210             else
6211                declare
6212                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6213
6214                begin
6215                   --  Build the condition for the explicit dereference case
6216
6217                   for Indx in 1 .. Ndims loop
6218                      Evolve_Or_Else
6219                        (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
6220                   end loop;
6221                end;
6222             end if;
6223          end if;
6224       end if;
6225
6226       --  Construct the test and insert into the tree
6227
6228       if Present (Cond) then
6229          if Do_Access then
6230             Cond := Guard_Access (Cond, Loc, Ck_Node);
6231          end if;
6232
6233          Add_Check
6234            (Make_Raise_Constraint_Error (Loc,
6235               Condition => Cond,
6236               Reason => CE_Length_Check_Failed));
6237       end if;
6238
6239       return Ret_Result;
6240    end Selected_Length_Checks;
6241
6242    ---------------------------
6243    -- Selected_Range_Checks --
6244    ---------------------------
6245
6246    function Selected_Range_Checks
6247      (Ck_Node    : Node_Id;
6248       Target_Typ : Entity_Id;
6249       Source_Typ : Entity_Id;
6250       Warn_Node  : Node_Id) return Check_Result
6251    is
6252       Loc         : constant Source_Ptr := Sloc (Ck_Node);
6253       S_Typ       : Entity_Id;
6254       T_Typ       : Entity_Id;
6255       Expr_Actual : Node_Id;
6256       Exptyp      : Entity_Id;
6257       Cond        : Node_Id := Empty;
6258       Do_Access   : Boolean := False;
6259       Wnode       : Node_Id  := Warn_Node;
6260       Ret_Result  : Check_Result := (Empty, Empty);
6261       Num_Checks  : Integer := 0;
6262
6263       procedure Add_Check (N : Node_Id);
6264       --  Adds the action given to Ret_Result if N is non-Empty
6265
6266       function Discrete_Range_Cond
6267         (Expr : Node_Id;
6268          Typ  : Entity_Id) return Node_Id;
6269       --  Returns expression to compute:
6270       --    Low_Bound (Expr) < Typ'First
6271       --      or else
6272       --    High_Bound (Expr) > Typ'Last
6273
6274       function Discrete_Expr_Cond
6275         (Expr : Node_Id;
6276          Typ  : Entity_Id) return Node_Id;
6277       --  Returns expression to compute:
6278       --    Expr < Typ'First
6279       --      or else
6280       --    Expr > Typ'Last
6281
6282       function Get_E_First_Or_Last
6283         (Loc  : Source_Ptr;
6284          E    : Entity_Id;
6285          Indx : Nat;
6286          Nam  : Name_Id) return Node_Id;
6287       --  Returns an attribute reference
6288       --    E'First or E'Last
6289       --  with a source location of Loc.
6290       --
6291       --  Nam is Name_First or Name_Last, according to which attribute is
6292       --  desired. If Indx is non-zero, it is passed as a literal in the
6293       --  Expressions of the attribute reference (identifying the desired
6294       --  array dimension).
6295
6296       function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
6297       function Get_N_Last  (N : Node_Id; Indx : Nat) return Node_Id;
6298       --  Returns expression to compute:
6299       --    N'First or N'Last using Duplicate_Subexpr_No_Checks
6300
6301       function Range_E_Cond
6302         (Exptyp : Entity_Id;
6303          Typ    : Entity_Id;
6304          Indx   : Nat)
6305          return   Node_Id;
6306       --  Returns expression to compute:
6307       --    Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
6308
6309       function Range_Equal_E_Cond
6310         (Exptyp : Entity_Id;
6311          Typ    : Entity_Id;
6312          Indx   : Nat) return Node_Id;
6313       --  Returns expression to compute:
6314       --    Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
6315
6316       function Range_N_Cond
6317         (Expr : Node_Id;
6318          Typ  : Entity_Id;
6319          Indx : Nat) return Node_Id;
6320       --  Return expression to compute:
6321       --    Expr'First < Typ'First or else Expr'Last > Typ'Last
6322
6323       ---------------
6324       -- Add_Check --
6325       ---------------
6326
6327       procedure Add_Check (N : Node_Id) is
6328       begin
6329          if Present (N) then
6330
6331             --  For now, ignore attempt to place more than 2 checks ???
6332
6333             if Num_Checks = 2 then
6334                return;
6335             end if;
6336
6337             pragma Assert (Num_Checks <= 1);
6338             Num_Checks := Num_Checks + 1;
6339             Ret_Result (Num_Checks) := N;
6340          end if;
6341       end Add_Check;
6342
6343       -------------------------
6344       -- Discrete_Expr_Cond --
6345       -------------------------
6346
6347       function Discrete_Expr_Cond
6348         (Expr : Node_Id;
6349          Typ  : Entity_Id) return Node_Id
6350       is
6351       begin
6352          return
6353            Make_Or_Else (Loc,
6354              Left_Opnd =>
6355                Make_Op_Lt (Loc,
6356                  Left_Opnd =>
6357                    Convert_To (Base_Type (Typ),
6358                      Duplicate_Subexpr_No_Checks (Expr)),
6359                  Right_Opnd =>
6360                    Convert_To (Base_Type (Typ),
6361                                Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
6362
6363              Right_Opnd =>
6364                Make_Op_Gt (Loc,
6365                  Left_Opnd =>
6366                    Convert_To (Base_Type (Typ),
6367                      Duplicate_Subexpr_No_Checks (Expr)),
6368                  Right_Opnd =>
6369                    Convert_To
6370                      (Base_Type (Typ),
6371                       Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
6372       end Discrete_Expr_Cond;
6373
6374       -------------------------
6375       -- Discrete_Range_Cond --
6376       -------------------------
6377
6378       function Discrete_Range_Cond
6379         (Expr : Node_Id;
6380          Typ  : Entity_Id) return Node_Id
6381       is
6382          LB : Node_Id := Low_Bound (Expr);
6383          HB : Node_Id := High_Bound (Expr);
6384
6385          Left_Opnd  : Node_Id;
6386          Right_Opnd : Node_Id;
6387
6388       begin
6389          if Nkind (LB) = N_Identifier
6390            and then Ekind (Entity (LB)) = E_Discriminant
6391          then
6392             LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6393          end if;
6394
6395          if Nkind (HB) = N_Identifier
6396            and then Ekind (Entity (HB)) = E_Discriminant
6397          then
6398             HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6399          end if;
6400
6401          Left_Opnd :=
6402            Make_Op_Lt (Loc,
6403              Left_Opnd  =>
6404                Convert_To
6405                  (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6406
6407              Right_Opnd =>
6408                Convert_To
6409                  (Base_Type (Typ),
6410                   Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
6411
6412          if Base_Type (Typ) = Typ then
6413             return Left_Opnd;
6414
6415          elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6416             and then
6417                Compile_Time_Known_Value (High_Bound (Scalar_Range
6418                                                      (Base_Type (Typ))))
6419          then
6420             if Is_Floating_Point_Type (Typ) then
6421                if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6422                   Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6423                then
6424                   return Left_Opnd;
6425                end if;
6426
6427             else
6428                if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6429                   Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6430                then
6431                   return Left_Opnd;
6432                end if;
6433             end if;
6434          end if;
6435
6436          Right_Opnd :=
6437            Make_Op_Gt (Loc,
6438              Left_Opnd  =>
6439                Convert_To
6440                  (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6441
6442              Right_Opnd =>
6443                Convert_To
6444                  (Base_Type (Typ),
6445                   Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
6446
6447          return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6448       end Discrete_Range_Cond;
6449
6450       -------------------------
6451       -- Get_E_First_Or_Last --
6452       -------------------------
6453
6454       function Get_E_First_Or_Last
6455         (Loc  : Source_Ptr;
6456          E    : Entity_Id;
6457          Indx : Nat;
6458          Nam  : Name_Id) return Node_Id
6459       is
6460          Exprs : List_Id;
6461       begin
6462          if Indx > 0 then
6463             Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
6464          else
6465             Exprs := No_List;
6466          end if;
6467
6468          return Make_Attribute_Reference (Loc,
6469                   Prefix         => New_Occurrence_Of (E, Loc),
6470                   Attribute_Name => Nam,
6471                   Expressions    => Exprs);
6472       end Get_E_First_Or_Last;
6473
6474       -----------------
6475       -- Get_N_First --
6476       -----------------
6477
6478       function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6479       begin
6480          return
6481            Make_Attribute_Reference (Loc,
6482              Attribute_Name => Name_First,
6483              Prefix =>
6484                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6485              Expressions => New_List (
6486                Make_Integer_Literal (Loc, Indx)));
6487       end Get_N_First;
6488
6489       ----------------
6490       -- Get_N_Last --
6491       ----------------
6492
6493       function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6494       begin
6495          return
6496            Make_Attribute_Reference (Loc,
6497              Attribute_Name => Name_Last,
6498              Prefix =>
6499                Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6500              Expressions => New_List (
6501               Make_Integer_Literal (Loc, Indx)));
6502       end Get_N_Last;
6503
6504       ------------------
6505       -- Range_E_Cond --
6506       ------------------
6507
6508       function Range_E_Cond
6509         (Exptyp : Entity_Id;
6510          Typ    : Entity_Id;
6511          Indx   : Nat) return Node_Id
6512       is
6513       begin
6514          return
6515            Make_Or_Else (Loc,
6516              Left_Opnd =>
6517                Make_Op_Lt (Loc,
6518                  Left_Opnd   =>
6519                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6520                  Right_Opnd  =>
6521                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6522
6523              Right_Opnd =>
6524                Make_Op_Gt (Loc,
6525                  Left_Opnd   =>
6526                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6527                  Right_Opnd  =>
6528                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6529       end Range_E_Cond;
6530
6531       ------------------------
6532       -- Range_Equal_E_Cond --
6533       ------------------------
6534
6535       function Range_Equal_E_Cond
6536         (Exptyp : Entity_Id;
6537          Typ    : Entity_Id;
6538          Indx   : Nat) return Node_Id
6539       is
6540       begin
6541          return
6542            Make_Or_Else (Loc,
6543              Left_Opnd =>
6544                Make_Op_Ne (Loc,
6545                  Left_Opnd   =>
6546                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
6547                  Right_Opnd  =>
6548                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6549
6550              Right_Opnd =>
6551                Make_Op_Ne (Loc,
6552                  Left_Opnd   =>
6553                    Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
6554                  Right_Opnd  =>
6555                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6556       end Range_Equal_E_Cond;
6557
6558       ------------------
6559       -- Range_N_Cond --
6560       ------------------
6561
6562       function Range_N_Cond
6563         (Expr : Node_Id;
6564          Typ  : Entity_Id;
6565          Indx : Nat) return Node_Id
6566       is
6567       begin
6568          return
6569            Make_Or_Else (Loc,
6570              Left_Opnd =>
6571                Make_Op_Lt (Loc,
6572                  Left_Opnd  =>
6573                    Get_N_First (Expr, Indx),
6574                  Right_Opnd =>
6575                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
6576
6577              Right_Opnd =>
6578                Make_Op_Gt (Loc,
6579                  Left_Opnd  =>
6580                    Get_N_Last (Expr, Indx),
6581                  Right_Opnd =>
6582                    Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
6583       end Range_N_Cond;
6584
6585    --  Start of processing for Selected_Range_Checks
6586
6587    begin
6588       if not Expander_Active then
6589          return Ret_Result;
6590       end if;
6591
6592       if Target_Typ = Any_Type
6593         or else Target_Typ = Any_Composite
6594         or else Raises_Constraint_Error (Ck_Node)
6595       then
6596          return Ret_Result;
6597       end if;
6598
6599       if No (Wnode) then
6600          Wnode := Ck_Node;
6601       end if;
6602
6603       T_Typ := Target_Typ;
6604
6605       if No (Source_Typ) then
6606          S_Typ := Etype (Ck_Node);
6607       else
6608          S_Typ := Source_Typ;
6609       end if;
6610
6611       if S_Typ = Any_Type or else S_Typ = Any_Composite then
6612          return Ret_Result;
6613       end if;
6614
6615       --  The order of evaluating T_Typ before S_Typ seems to be critical
6616       --  because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6617       --  in, and since Node can be an N_Range node, it might be invalid.
6618       --  Should there be an assert check somewhere for taking the Etype of
6619       --  an N_Range node ???
6620
6621       if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6622          S_Typ := Designated_Type (S_Typ);
6623          T_Typ := Designated_Type (T_Typ);
6624          Do_Access := True;
6625
6626          --  A simple optimization for the null case
6627
6628          if Known_Null (Ck_Node) then
6629             return Ret_Result;
6630          end if;
6631       end if;
6632
6633       --  For an N_Range Node, check for a null range and then if not
6634       --  null generate a range check action.
6635
6636       if Nkind (Ck_Node) = N_Range then
6637
6638          --  There's no point in checking a range against itself
6639
6640          if Ck_Node = Scalar_Range (T_Typ) then
6641             return Ret_Result;
6642          end if;
6643
6644          declare
6645             T_LB       : constant Node_Id := Type_Low_Bound  (T_Typ);
6646             T_HB       : constant Node_Id := Type_High_Bound (T_Typ);
6647             Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
6648             Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
6649
6650             LB         : Node_Id := Low_Bound (Ck_Node);
6651             HB         : Node_Id := High_Bound (Ck_Node);
6652             Known_LB   : Boolean;
6653             Known_HB   : Boolean;
6654
6655             Null_Range     : Boolean;
6656             Out_Of_Range_L : Boolean;
6657             Out_Of_Range_H : Boolean;
6658
6659          begin
6660             --  Compute what is known at compile time
6661
6662             if Known_T_LB and Known_T_HB then
6663                if Compile_Time_Known_Value (LB) then
6664                   Known_LB := True;
6665
6666                --  There's no point in checking that a bound is within its
6667                --  own range so pretend that it is known in this case. First
6668                --  deal with low bound.
6669
6670                elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
6671                  and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
6672                then
6673                   LB := T_LB;
6674                   Known_LB := True;
6675
6676                else
6677                   Known_LB := False;
6678                end if;
6679
6680                --  Likewise for the high bound
6681
6682                if Compile_Time_Known_Value (HB) then
6683                   Known_HB := True;
6684
6685                elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
6686                  and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
6687                then
6688                   HB := T_HB;
6689                   Known_HB := True;
6690
6691                else
6692                   Known_HB := False;
6693                end if;
6694             end if;
6695
6696             --  Check for case where everything is static and we can do the
6697             --  check at compile time. This is skipped if we have an access
6698             --  type, since the access value may be null.
6699
6700             --  ??? This code can be improved since you only need to know that
6701             --  the two respective bounds (LB & T_LB or HB & T_HB) are known at
6702             --  compile time to emit pertinent messages.
6703
6704             if Known_T_LB and Known_T_HB and Known_LB and Known_HB
6705               and not Do_Access
6706             then
6707                --  Floating-point case
6708
6709                if Is_Floating_Point_Type (S_Typ) then
6710                   Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6711                   Out_Of_Range_L :=
6712                     (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6713                       or else
6714                     (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6715
6716                   Out_Of_Range_H :=
6717                     (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6718                       or else
6719                     (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6720
6721                --  Fixed or discrete type case
6722
6723                else
6724                   Null_Range := Expr_Value (HB) < Expr_Value (LB);
6725                   Out_Of_Range_L :=
6726                     (Expr_Value (LB) < Expr_Value (T_LB))
6727                       or else
6728                     (Expr_Value (LB) > Expr_Value (T_HB));
6729
6730                   Out_Of_Range_H :=
6731                     (Expr_Value (HB) > Expr_Value (T_HB))
6732                       or else
6733                     (Expr_Value (HB) < Expr_Value (T_LB));
6734                end if;
6735
6736                if not Null_Range then
6737                   if Out_Of_Range_L then
6738                      if No (Warn_Node) then
6739                         Add_Check
6740                           (Compile_Time_Constraint_Error
6741                              (Low_Bound (Ck_Node),
6742                               "static value out of range of}?", T_Typ));
6743
6744                      else
6745                         Add_Check
6746                           (Compile_Time_Constraint_Error
6747                             (Wnode,
6748                              "static range out of bounds of}?", T_Typ));
6749                      end if;
6750                   end if;
6751
6752                   if Out_Of_Range_H then
6753                      if No (Warn_Node) then
6754                         Add_Check
6755                           (Compile_Time_Constraint_Error
6756                              (High_Bound (Ck_Node),
6757                               "static value out of range of}?", T_Typ));
6758
6759                      else
6760                         Add_Check
6761                           (Compile_Time_Constraint_Error
6762                              (Wnode,
6763                               "static range out of bounds of}?", T_Typ));
6764                      end if;
6765                   end if;
6766                end if;
6767
6768             else
6769                declare
6770                   LB : Node_Id := Low_Bound (Ck_Node);
6771                   HB : Node_Id := High_Bound (Ck_Node);
6772
6773                begin
6774                   --  If either bound is a discriminant and we are within the
6775                   --  record declaration, it is a use of the discriminant in a
6776                   --  constraint of a component, and nothing can be checked
6777                   --  here. The check will be emitted within the init proc.
6778                   --  Before then, the discriminal has no real meaning.
6779                   --  Similarly, if the entity is a discriminal, there is no
6780                   --  check to perform yet.
6781
6782                   --  The same holds within a discriminated synchronized type,
6783                   --  where the discriminant may constrain a component or an
6784                   --  entry family.
6785
6786                   if Nkind (LB) = N_Identifier
6787                     and then Denotes_Discriminant (LB, True)
6788                   then
6789                      if Current_Scope = Scope (Entity (LB))
6790                        or else Is_Concurrent_Type (Current_Scope)
6791                        or else Ekind (Entity (LB)) /= E_Discriminant
6792                      then
6793                         return Ret_Result;
6794                      else
6795                         LB :=
6796                           New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6797                      end if;
6798                   end if;
6799
6800                   if Nkind (HB) = N_Identifier
6801                     and then Denotes_Discriminant (HB, True)
6802                   then
6803                      if Current_Scope = Scope (Entity (HB))
6804                        or else Is_Concurrent_Type (Current_Scope)
6805                        or else Ekind (Entity (HB)) /= E_Discriminant
6806                      then
6807                         return Ret_Result;
6808                      else
6809                         HB :=
6810                           New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6811                      end if;
6812                   end if;
6813
6814                   Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6815                   Set_Paren_Count (Cond, 1);
6816
6817                   Cond :=
6818                     Make_And_Then (Loc,
6819                       Left_Opnd =>
6820                         Make_Op_Ge (Loc,
6821                           Left_Opnd  => Duplicate_Subexpr_No_Checks (HB),
6822                           Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6823                       Right_Opnd => Cond);
6824                end;
6825             end if;
6826          end;
6827
6828       elsif Is_Scalar_Type (S_Typ) then
6829
6830          --  This somewhat duplicates what Apply_Scalar_Range_Check does,
6831          --  except the above simply sets a flag in the node and lets
6832          --  gigi generate the check base on the Etype of the expression.
6833          --  Sometimes, however we want to do a dynamic check against an
6834          --  arbitrary target type, so we do that here.
6835
6836          if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6837             Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6838
6839          --  For literals, we can tell if the constraint error will be
6840          --  raised at compile time, so we never need a dynamic check, but
6841          --  if the exception will be raised, then post the usual warning,
6842          --  and replace the literal with a raise constraint error
6843          --  expression. As usual, skip this for access types
6844
6845          elsif Compile_Time_Known_Value (Ck_Node)
6846            and then not Do_Access
6847          then
6848             declare
6849                LB : constant Node_Id := Type_Low_Bound (T_Typ);
6850                UB : constant Node_Id := Type_High_Bound (T_Typ);
6851
6852                Out_Of_Range  : Boolean;
6853                Static_Bounds : constant Boolean :=
6854                                  Compile_Time_Known_Value (LB)
6855                                    and Compile_Time_Known_Value (UB);
6856
6857             begin
6858                --  Following range tests should use Sem_Eval routine ???
6859
6860                if Static_Bounds then
6861                   if Is_Floating_Point_Type (S_Typ) then
6862                      Out_Of_Range :=
6863                        (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6864                          or else
6865                        (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6866
6867                   --  Fixed or discrete type
6868
6869                   else
6870                      Out_Of_Range :=
6871                        Expr_Value (Ck_Node) < Expr_Value (LB)
6872                          or else
6873                        Expr_Value (Ck_Node) > Expr_Value (UB);
6874                   end if;
6875
6876                   --  Bounds of the type are static and the literal is out of
6877                   --  range so output a warning message.
6878
6879                   if Out_Of_Range then
6880                      if No (Warn_Node) then
6881                         Add_Check
6882                           (Compile_Time_Constraint_Error
6883                              (Ck_Node,
6884                               "static value out of range of}?", T_Typ));
6885
6886                      else
6887                         Add_Check
6888                           (Compile_Time_Constraint_Error
6889                              (Wnode,
6890                               "static value out of range of}?", T_Typ));
6891                      end if;
6892                   end if;
6893
6894                else
6895                   Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6896                end if;
6897             end;
6898
6899          --  Here for the case of a non-static expression, we need a runtime
6900          --  check unless the source type range is guaranteed to be in the
6901          --  range of the target type.
6902
6903          else
6904             if not In_Subrange_Of (S_Typ, T_Typ) then
6905                Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6906             end if;
6907          end if;
6908       end if;
6909
6910       if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6911          if Is_Constrained (T_Typ) then
6912
6913             Expr_Actual := Get_Referenced_Object (Ck_Node);
6914             Exptyp      := Get_Actual_Subtype (Expr_Actual);
6915
6916             if Is_Access_Type (Exptyp) then
6917                Exptyp := Designated_Type (Exptyp);
6918             end if;
6919
6920             --  String_Literal case. This needs to be handled specially be-
6921             --  cause no index types are available for string literals. The
6922             --  condition is simply:
6923
6924             --    T_Typ'Length = string-literal-length
6925
6926             if Nkind (Expr_Actual) = N_String_Literal then
6927                null;
6928
6929             --  General array case. Here we have a usable actual subtype for
6930             --  the expression, and the condition is built from the two types
6931
6932             --     T_Typ'First     < Exptyp'First     or else
6933             --     T_Typ'Last      > Exptyp'Last      or else
6934             --     T_Typ'First(1)  < Exptyp'First(1)  or else
6935             --     T_Typ'Last(1)   > Exptyp'Last(1)   or else
6936             --     ...
6937
6938             elsif Is_Constrained (Exptyp) then
6939                declare
6940                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6941
6942                   L_Index : Node_Id;
6943                   R_Index : Node_Id;
6944
6945                begin
6946                   L_Index := First_Index (T_Typ);
6947                   R_Index := First_Index (Exptyp);
6948
6949                   for Indx in 1 .. Ndims loop
6950                      if not (Nkind (L_Index) = N_Raise_Constraint_Error
6951                                or else
6952                              Nkind (R_Index) = N_Raise_Constraint_Error)
6953                      then
6954                         --  Deal with compile time length check. Note that we
6955                         --  skip this in the access case, because the access
6956                         --  value may be null, so we cannot know statically.
6957
6958                         if not
6959                           Subtypes_Statically_Match
6960                             (Etype (L_Index), Etype (R_Index))
6961                         then
6962                            --  If the target type is constrained then we
6963                            --  have to check for exact equality of bounds
6964                            --  (required for qualified expressions).
6965
6966                            if Is_Constrained (T_Typ) then
6967                               Evolve_Or_Else
6968                                 (Cond,
6969                                  Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6970                            else
6971                               Evolve_Or_Else
6972                                 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6973                            end if;
6974                         end if;
6975
6976                         Next (L_Index);
6977                         Next (R_Index);
6978                      end if;
6979                   end loop;
6980                end;
6981
6982             --  Handle cases where we do not get a usable actual subtype that
6983             --  is constrained. This happens for example in the function call
6984             --  and explicit dereference cases. In these cases, we have to get
6985             --  the length or range from the expression itself, making sure we
6986             --  do not evaluate it more than once.
6987
6988             --  Here Ck_Node is the original expression, or more properly the
6989             --  result of applying Duplicate_Expr to the original tree,
6990             --  forcing the result to be a name.
6991
6992             else
6993                declare
6994                   Ndims : constant Nat := Number_Dimensions (T_Typ);
6995
6996                begin
6997                   --  Build the condition for the explicit dereference case
6998
6999                   for Indx in 1 .. Ndims loop
7000                      Evolve_Or_Else
7001                        (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
7002                   end loop;
7003                end;
7004             end if;
7005
7006          else
7007             --  For a conversion to an unconstrained array type, generate an
7008             --  Action to check that the bounds of the source value are within
7009             --  the constraints imposed by the target type (RM 4.6(38)). No
7010             --  check is needed for a conversion to an access to unconstrained
7011             --  array type, as 4.6(24.15/2) requires the designated subtypes
7012             --  of the two access types to statically match.
7013
7014             if Nkind (Parent (Ck_Node)) = N_Type_Conversion
7015               and then not Do_Access
7016             then
7017                declare
7018                   Opnd_Index : Node_Id;
7019                   Targ_Index : Node_Id;
7020                   Opnd_Range : Node_Id;
7021
7022                begin
7023                   Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
7024                   Targ_Index := First_Index (T_Typ);
7025                   while Present (Opnd_Index) loop
7026
7027                      --  If the index is a range, use its bounds. If it is an
7028                      --  entity (as will be the case if it is a named subtype
7029                      --  or an itype created for a slice) retrieve its range.
7030
7031                      if Is_Entity_Name (Opnd_Index)
7032                        and then Is_Type (Entity (Opnd_Index))
7033                      then
7034                         Opnd_Range := Scalar_Range (Entity (Opnd_Index));
7035                      else
7036                         Opnd_Range := Opnd_Index;
7037                      end if;
7038
7039                      if Nkind (Opnd_Range) = N_Range then
7040                         if  Is_In_Range
7041                              (Low_Bound (Opnd_Range), Etype (Targ_Index),
7042                               Assume_Valid => True)
7043                           and then
7044                             Is_In_Range
7045                              (High_Bound (Opnd_Range), Etype (Targ_Index),
7046                               Assume_Valid => True)
7047                         then
7048                            null;
7049
7050                         --  If null range, no check needed
7051
7052                         elsif
7053                           Compile_Time_Known_Value (High_Bound (Opnd_Range))
7054                             and then
7055                           Compile_Time_Known_Value (Low_Bound (Opnd_Range))
7056                             and then
7057                               Expr_Value (High_Bound (Opnd_Range)) <
7058                                   Expr_Value (Low_Bound (Opnd_Range))
7059                         then
7060                            null;
7061
7062                         elsif Is_Out_Of_Range
7063                                 (Low_Bound (Opnd_Range), Etype (Targ_Index),
7064                                  Assume_Valid => True)
7065                           or else
7066                               Is_Out_Of_Range
7067                                 (High_Bound (Opnd_Range), Etype (Targ_Index),
7068                                  Assume_Valid => True)
7069                         then
7070                            Add_Check
7071                              (Compile_Time_Constraint_Error
7072                                (Wnode, "value out of range of}?", T_Typ));
7073
7074                         else
7075                            Evolve_Or_Else
7076                              (Cond,
7077                               Discrete_Range_Cond
7078                                 (Opnd_Range, Etype (Targ_Index)));
7079                         end if;
7080                      end if;
7081
7082                      Next_Index (Opnd_Index);
7083                      Next_Index (Targ_Index);
7084                   end loop;
7085                end;
7086             end if;
7087          end if;
7088       end if;
7089
7090       --  Construct the test and insert into the tree
7091
7092       if Present (Cond) then
7093          if Do_Access then
7094             Cond := Guard_Access (Cond, Loc, Ck_Node);
7095          end if;
7096
7097          Add_Check
7098            (Make_Raise_Constraint_Error (Loc,
7099              Condition => Cond,
7100              Reason    => CE_Range_Check_Failed));
7101       end if;
7102
7103       return Ret_Result;
7104    end Selected_Range_Checks;
7105
7106    -------------------------------
7107    -- Storage_Checks_Suppressed --
7108    -------------------------------
7109
7110    function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
7111    begin
7112       if Present (E) and then Checks_May_Be_Suppressed (E) then
7113          return Is_Check_Suppressed (E, Storage_Check);
7114       else
7115          return Scope_Suppress (Storage_Check);
7116       end if;
7117    end Storage_Checks_Suppressed;
7118
7119    ---------------------------
7120    -- Tag_Checks_Suppressed --
7121    ---------------------------
7122
7123    function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
7124    begin
7125       if Present (E) then
7126          if Kill_Tag_Checks (E) then
7127             return True;
7128          elsif Checks_May_Be_Suppressed (E) then
7129             return Is_Check_Suppressed (E, Tag_Check);
7130          end if;
7131       end if;
7132
7133       return Scope_Suppress (Tag_Check);
7134    end Tag_Checks_Suppressed;
7135
7136    --------------------------
7137    -- Validity_Check_Range --
7138    --------------------------
7139
7140    procedure Validity_Check_Range (N : Node_Id) is
7141    begin
7142       if Validity_Checks_On and Validity_Check_Operands then
7143          if Nkind (N) = N_Range then
7144             Ensure_Valid (Low_Bound (N));
7145             Ensure_Valid (High_Bound (N));
7146          end if;
7147       end if;
7148    end Validity_Check_Range;
7149
7150    --------------------------------
7151    -- Validity_Checks_Suppressed --
7152    --------------------------------
7153
7154    function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
7155    begin
7156       if Present (E) and then Checks_May_Be_Suppressed (E) then
7157          return Is_Check_Suppressed (E, Validity_Check);
7158       else
7159          return Scope_Suppress (Validity_Check);
7160       end if;
7161    end Validity_Checks_Suppressed;
7162
7163 end Checks;