OSDN Git Service

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