OSDN Git Service

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