OSDN Git Service

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