OSDN Git Service

2009-04-08 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_eval.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ E V A L                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2008, 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 Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Eval_Fat; use Eval_Fat;
33 with Exp_Util; use Exp_Util;
34 with Lib;      use Lib;
35 with Namet;    use Namet;
36 with Nmake;    use Nmake;
37 with Nlists;   use Nlists;
38 with Opt;      use Opt;
39 with Sem;      use Sem;
40 with Sem_Cat;  use Sem_Cat;
41 with Sem_Ch6;  use Sem_Ch6;
42 with Sem_Ch8;  use Sem_Ch8;
43 with Sem_Res;  use Sem_Res;
44 with Sem_Util; use Sem_Util;
45 with Sem_Type; use Sem_Type;
46 with Sem_Warn; use Sem_Warn;
47 with Sinfo;    use Sinfo;
48 with Snames;   use Snames;
49 with Stand;    use Stand;
50 with Stringt;  use Stringt;
51 with Tbuild;   use Tbuild;
52
53 package body Sem_Eval is
54
55    -----------------------------------------
56    -- Handling of Compile Time Evaluation --
57    -----------------------------------------
58
59    --  The compile time evaluation of expressions is distributed over several
60    --  Eval_xxx procedures. These procedures are called immediately after
61    --  a subexpression is resolved and is therefore accomplished in a bottom
62    --  up fashion. The flags are synthesized using the following approach.
63
64    --    Is_Static_Expression is determined by following the detailed rules
65    --    in RM 4.9(4-14). This involves testing the Is_Static_Expression
66    --    flag of the operands in many cases.
67
68    --    Raises_Constraint_Error is set if any of the operands have the flag
69    --    set or if an attempt to compute the value of the current expression
70    --    results in detection of a runtime constraint error.
71
72    --  As described in the spec, the requirement is that Is_Static_Expression
73    --  be accurately set, and in addition for nodes for which this flag is set,
74    --  Raises_Constraint_Error must also be set. Furthermore a node which has
75    --  Is_Static_Expression set, and Raises_Constraint_Error clear, then the
76    --  requirement is that the expression value must be precomputed, and the
77    --  node is either a literal, or the name of a constant entity whose value
78    --  is a static expression.
79
80    --  The general approach is as follows. First compute Is_Static_Expression.
81    --  If the node is not static, then the flag is left off in the node and
82    --  we are all done. Otherwise for a static node, we test if any of the
83    --  operands will raise constraint error, and if so, propagate the flag
84    --  Raises_Constraint_Error to the result node and we are done (since the
85    --  error was already posted at a lower level).
86
87    --  For the case of a static node whose operands do not raise constraint
88    --  error, we attempt to evaluate the node. If this evaluation succeeds,
89    --  then the node is replaced by the result of this computation. If the
90    --  evaluation raises constraint error, then we rewrite the node with
91    --  Apply_Compile_Time_Constraint_Error to raise the exception and also
92    --  to post appropriate error messages.
93
94    ----------------
95    -- Local Data --
96    ----------------
97
98    type Bits is array (Nat range <>) of Boolean;
99    --  Used to convert unsigned (modular) values for folding logical ops
100
101    --  The following definitions are used to maintain a cache of nodes that
102    --  have compile time known values. The cache is maintained only for
103    --  discrete types (the most common case), and is populated by calls to
104    --  Compile_Time_Known_Value and Expr_Value, but only used by Expr_Value
105    --  since it is possible for the status to change (in particular it is
106    --  possible for a node to get replaced by a constraint error node).
107
108    CV_Bits : constant := 5;
109    --  Number of low order bits of Node_Id value used to reference entries
110    --  in the cache table.
111
112    CV_Cache_Size : constant Nat := 2 ** CV_Bits;
113    --  Size of cache for compile time values
114
115    subtype CV_Range is Nat range 0 .. CV_Cache_Size;
116
117    type CV_Entry is record
118       N : Node_Id;
119       V : Uint;
120    end record;
121
122    type CV_Cache_Array is array (CV_Range) of CV_Entry;
123
124    CV_Cache : CV_Cache_Array := (others => (Node_High_Bound, Uint_0));
125    --  This is the actual cache, with entries consisting of node/value pairs,
126    --  and the impossible value Node_High_Bound used for unset entries.
127
128    -----------------------
129    -- Local Subprograms --
130    -----------------------
131
132    function From_Bits (B : Bits; T : Entity_Id) return Uint;
133    --  Converts a bit string of length B'Length to a Uint value to be used
134    --  for a target of type T, which is a modular type. This procedure
135    --  includes the necessary reduction by the modulus in the case of a
136    --  non-binary modulus (for a binary modulus, the bit string is the
137    --  right length any way so all is well).
138
139    function Get_String_Val (N : Node_Id) return Node_Id;
140    --  Given a tree node for a folded string or character value, returns
141    --  the corresponding string literal or character literal (one of the
142    --  two must be available, or the operand would not have been marked
143    --  as foldable in the earlier analysis of the operation).
144
145    function OK_Bits (N : Node_Id; Bits : Uint) return Boolean;
146    --  Bits represents the number of bits in an integer value to be computed
147    --  (but the value has not been computed yet). If this value in Bits is
148    --  reasonable, a result of True is returned, with the implication that
149    --  the caller should go ahead and complete the calculation. If the value
150    --  in Bits is unreasonably large, then an error is posted on node N, and
151    --  False is returned (and the caller skips the proposed calculation).
152
153    procedure Out_Of_Range (N : Node_Id);
154    --  This procedure is called if it is determined that node N, which
155    --  appears in a non-static context, is a compile time known value
156    --  which is outside its range, i.e. the range of Etype. This is used
157    --  in contexts where this is an illegality if N is static, and should
158    --  generate a warning otherwise.
159
160    procedure Rewrite_In_Raise_CE (N : Node_Id; Exp : Node_Id);
161    --  N and Exp are nodes representing an expression, Exp is known
162    --  to raise CE. N is rewritten in term of Exp in the optimal way.
163
164    function String_Type_Len (Stype : Entity_Id) return Uint;
165    --  Given a string type, determines the length of the index type, or,
166    --  if this index type is non-static, the length of the base type of
167    --  this index type. Note that if the string type is itself static,
168    --  then the index type is static, so the second case applies only
169    --  if the string type passed is non-static.
170
171    function Test (Cond : Boolean) return Uint;
172    pragma Inline (Test);
173    --  This function simply returns the appropriate Boolean'Pos value
174    --  corresponding to the value of Cond as a universal integer. It is
175    --  used for producing the result of the static evaluation of the
176    --  logical operators
177
178    procedure Test_Expression_Is_Foldable
179      (N    : Node_Id;
180       Op1  : Node_Id;
181       Stat : out Boolean;
182       Fold : out Boolean);
183    --  Tests to see if expression N whose single operand is Op1 is foldable,
184    --  i.e. the operand value is known at compile time. If the operation is
185    --  foldable, then Fold is True on return, and Stat indicates whether
186    --  the result is static (i.e. both operands were static). Note that it
187    --  is quite possible for Fold to be True, and Stat to be False, since
188    --  there are cases in which we know the value of an operand even though
189    --  it is not technically static (e.g. the static lower bound of a range
190    --  whose upper bound is non-static).
191    --
192    --  If Stat is set False on return, then Test_Expression_Is_Foldable makes a
193    --  call to Check_Non_Static_Context on the operand. If Fold is False on
194    --  return, then all processing is complete, and the caller should
195    --  return, since there is nothing else to do.
196
197    procedure Test_Expression_Is_Foldable
198      (N    : Node_Id;
199       Op1  : Node_Id;
200       Op2  : Node_Id;
201       Stat : out Boolean;
202       Fold : out Boolean);
203    --  Same processing, except applies to an expression N with two operands
204    --  Op1 and Op2.
205
206    procedure To_Bits (U : Uint; B : out Bits);
207    --  Converts a Uint value to a bit string of length B'Length
208
209    ------------------------------
210    -- Check_Non_Static_Context --
211    ------------------------------
212
213    procedure Check_Non_Static_Context (N : Node_Id) is
214       T         : constant Entity_Id := Etype (N);
215       Checks_On : constant Boolean   :=
216                     not Index_Checks_Suppressed (T)
217                       and not Range_Checks_Suppressed (T);
218
219    begin
220       --  Ignore cases of non-scalar types or error types
221
222       if T = Any_Type or else not Is_Scalar_Type (T) then
223          return;
224       end if;
225
226       --  At this stage we have a scalar type. If we have an expression
227       --  that raises CE, then we already issued a warning or error msg
228       --  so there is nothing more to be done in this routine.
229
230       if Raises_Constraint_Error (N) then
231          return;
232       end if;
233
234       --  Now we have a scalar type which is not marked as raising a
235       --  constraint error exception. The main purpose of this routine
236       --  is to deal with static expressions appearing in a non-static
237       --  context. That means that if we do not have a static expression
238       --  then there is not much to do. The one case that we deal with
239       --  here is that if we have a floating-point value that is out of
240       --  range, then we post a warning that an infinity will result.
241
242       if not Is_Static_Expression (N) then
243          if Is_Floating_Point_Type (T)
244            and then Is_Out_Of_Range (N, Base_Type (T), Assume_Valid => True)
245          then
246             Error_Msg_N
247               ("?float value out of range, infinity will be generated", N);
248          end if;
249
250          return;
251       end if;
252
253       --  Here we have the case of outer level static expression of
254       --  scalar type, where the processing of this procedure is needed.
255
256       --  For real types, this is where we convert the value to a machine
257       --  number (see RM 4.9(38)). Also see ACVC test C490001. We should
258       --  only need to do this if the parent is a constant declaration,
259       --  since in other cases, gigi should do the necessary conversion
260       --  correctly, but experimentation shows that this is not the case
261       --  on all machines, in particular if we do not convert all literals
262       --  to machine values in non-static contexts, then ACVC test C490001
263       --  fails on Sparc/Solaris and SGI/Irix.
264
265       if Nkind (N) = N_Real_Literal
266         and then not Is_Machine_Number (N)
267         and then not Is_Generic_Type (Etype (N))
268         and then Etype (N) /= Universal_Real
269       then
270          --  Check that value is in bounds before converting to machine
271          --  number, so as not to lose case where value overflows in the
272          --  least significant bit or less. See B490001.
273
274          if Is_Out_Of_Range (N, Base_Type (T), Assume_Valid => True) then
275             Out_Of_Range (N);
276             return;
277          end if;
278
279          --  Note: we have to copy the node, to avoid problems with conformance
280          --  of very similar numbers (see ACVC tests B4A010C and B63103A).
281
282          Rewrite (N, New_Copy (N));
283
284          if not Is_Floating_Point_Type (T) then
285             Set_Realval
286               (N, Corresponding_Integer_Value (N) * Small_Value (T));
287
288          elsif not UR_Is_Zero (Realval (N)) then
289
290             --  Note: even though RM 4.9(38) specifies biased rounding,
291             --  this has been modified by AI-100 in order to prevent
292             --  confusing differences in rounding between static and
293             --  non-static expressions. AI-100 specifies that the effect
294             --  of such rounding is implementation dependent, and in GNAT
295             --  we round to nearest even to match the run-time behavior.
296
297             Set_Realval
298               (N, Machine (Base_Type (T), Realval (N), Round_Even, N));
299          end if;
300
301          Set_Is_Machine_Number (N);
302       end if;
303
304       --  Check for out of range universal integer. This is a non-static
305       --  context, so the integer value must be in range of the runtime
306       --  representation of universal integers.
307
308       --  We do this only within an expression, because that is the only
309       --  case in which non-static universal integer values can occur, and
310       --  furthermore, Check_Non_Static_Context is currently (incorrectly???)
311       --  called in contexts like the expression of a number declaration where
312       --  we certainly want to allow out of range values.
313
314       if Etype (N) = Universal_Integer
315         and then Nkind (N) = N_Integer_Literal
316         and then Nkind (Parent (N)) in N_Subexpr
317         and then
318           (Intval (N) < Expr_Value (Type_Low_Bound (Universal_Integer))
319             or else
320            Intval (N) > Expr_Value (Type_High_Bound (Universal_Integer)))
321       then
322          Apply_Compile_Time_Constraint_Error
323            (N, "non-static universal integer value out of range?",
324             CE_Range_Check_Failed);
325
326       --  Check out of range of base type
327
328       elsif Is_Out_Of_Range (N, Base_Type (T), Assume_Valid => True) then
329          Out_Of_Range (N);
330
331       --  Give warning if outside subtype (where one or both of the bounds of
332       --  the subtype is static). This warning is omitted if the expression
333       --  appears in a range that could be null (warnings are handled elsewhere
334       --  for this case).
335
336       elsif T /= Base_Type (T)
337         and then Nkind (Parent (N)) /= N_Range
338       then
339          if Is_In_Range (N, T, Assume_Valid => True) then
340             null;
341
342          elsif Is_Out_Of_Range (N, T, Assume_Valid => True) then
343             Apply_Compile_Time_Constraint_Error
344               (N, "value not in range of}?", CE_Range_Check_Failed);
345
346          elsif Checks_On then
347             Enable_Range_Check (N);
348
349          else
350             Set_Do_Range_Check (N, False);
351          end if;
352       end if;
353    end Check_Non_Static_Context;
354
355    ---------------------------------
356    -- Check_String_Literal_Length --
357    ---------------------------------
358
359    procedure Check_String_Literal_Length (N : Node_Id; Ttype : Entity_Id) is
360    begin
361       if not Raises_Constraint_Error (N)
362         and then Is_Constrained (Ttype)
363       then
364          if
365            UI_From_Int (String_Length (Strval (N))) /= String_Type_Len (Ttype)
366          then
367             Apply_Compile_Time_Constraint_Error
368               (N, "string length wrong for}?",
369                CE_Length_Check_Failed,
370                Ent => Ttype,
371                Typ => Ttype);
372          end if;
373       end if;
374    end Check_String_Literal_Length;
375
376    --------------------------
377    -- Compile_Time_Compare --
378    --------------------------
379
380    function Compile_Time_Compare
381      (L, R         : Node_Id;
382       Assume_Valid : Boolean;
383       Rec          : Boolean := False) return Compare_Result
384    is
385       Ltyp : Entity_Id := Etype (L);
386       Rtyp : Entity_Id := Etype (R);
387       --  These get reset to the base type for the case of entities where
388       --  Is_Known_Valid is not set. This takes care of handling possible
389       --  invalid representations using the value of the base type, in
390       --  accordance with RM 13.9.1(10).
391
392       procedure Compare_Decompose
393         (N : Node_Id;
394          R : out Node_Id;
395          V : out Uint);
396       --  This procedure decomposes the node N into an expression node and a
397       --  signed offset, so that the value of N is equal to the value of R plus
398       --  the value V (which may be negative). If no such decomposition is
399       --  possible, then on return R is a copy of N, and V is set to zero.
400
401       function Compare_Fixup (N : Node_Id) return Node_Id;
402       --  This function deals with replacing 'Last and 'First references with
403       --  their corresponding type bounds, which we then can compare. The
404       --  argument is the original node, the result is the identity, unless we
405       --  have a 'Last/'First reference in which case the value returned is the
406       --  appropriate type bound.
407
408       function Is_Same_Value (L, R : Node_Id) return Boolean;
409       --  Returns True iff L and R represent expressions that definitely
410       --  have identical (but not necessarily compile time known) values
411       --  Indeed the caller is expected to have already dealt with the
412       --  cases of compile time known values, so these are not tested here.
413
414       -----------------------
415       -- Compare_Decompose --
416       -----------------------
417
418       procedure Compare_Decompose
419         (N : Node_Id;
420          R : out Node_Id;
421          V : out Uint)
422       is
423       begin
424          if Nkind (N) = N_Op_Add
425            and then Nkind (Right_Opnd (N)) = N_Integer_Literal
426          then
427             R := Left_Opnd (N);
428             V := Intval (Right_Opnd (N));
429             return;
430
431          elsif Nkind (N) = N_Op_Subtract
432            and then Nkind (Right_Opnd (N)) = N_Integer_Literal
433          then
434             R := Left_Opnd (N);
435             V := UI_Negate (Intval (Right_Opnd (N)));
436             return;
437
438          elsif Nkind (N) = N_Attribute_Reference  then
439             if Attribute_Name (N) = Name_Succ then
440                R := First (Expressions (N));
441                V := Uint_1;
442                return;
443
444             elsif Attribute_Name (N) = Name_Pred then
445                R := First (Expressions (N));
446                V := Uint_Minus_1;
447                return;
448             end if;
449          end if;
450
451          R := N;
452          V := Uint_0;
453       end Compare_Decompose;
454
455       -------------------
456       -- Compare_Fixup --
457       -------------------
458
459       function Compare_Fixup (N : Node_Id) return Node_Id is
460          Indx : Node_Id;
461          Xtyp : Entity_Id;
462          Subs : Nat;
463
464       begin
465          if Nkind (N) = N_Attribute_Reference
466            and then (Attribute_Name (N) = Name_First
467                        or else
468                      Attribute_Name (N) = Name_Last)
469          then
470             Xtyp := Etype (Prefix (N));
471
472             --  If we have no type, then just abandon the attempt to do
473             --  a fixup, this is probably the result of some other error.
474
475             if No (Xtyp) then
476                return N;
477             end if;
478
479             --  Dereference an access type
480
481             if Is_Access_Type (Xtyp) then
482                Xtyp := Designated_Type (Xtyp);
483             end if;
484
485             --  If we don't have an array type at this stage, something
486             --  is peculiar, e.g. another error, and we abandon the attempt
487             --  at a fixup.
488
489             if not Is_Array_Type (Xtyp) then
490                return N;
491             end if;
492
493             --  Ignore unconstrained array, since bounds are not meaningful
494
495             if not Is_Constrained (Xtyp) then
496                return N;
497             end if;
498
499             if Ekind (Xtyp) = E_String_Literal_Subtype then
500                if Attribute_Name (N) = Name_First then
501                   return String_Literal_Low_Bound (Xtyp);
502
503                else         -- Attribute_Name (N) = Name_Last
504                   return Make_Integer_Literal (Sloc (N),
505                     Intval => Intval (String_Literal_Low_Bound (Xtyp))
506                        + String_Literal_Length (Xtyp));
507                end if;
508             end if;
509
510             --  Find correct index type
511
512             Indx := First_Index (Xtyp);
513
514             if Present (Expressions (N)) then
515                Subs := UI_To_Int (Expr_Value (First (Expressions (N))));
516
517                for J in 2 .. Subs loop
518                   Indx := Next_Index (Indx);
519                end loop;
520             end if;
521
522             Xtyp := Etype (Indx);
523
524             if Attribute_Name (N) = Name_First then
525                return Type_Low_Bound (Xtyp);
526
527             else -- Attribute_Name (N) = Name_Last
528                return Type_High_Bound (Xtyp);
529             end if;
530          end if;
531
532          return N;
533       end Compare_Fixup;
534
535       -------------------
536       -- Is_Same_Value --
537       -------------------
538
539       function Is_Same_Value (L, R : Node_Id) return Boolean is
540          Lf : constant Node_Id := Compare_Fixup (L);
541          Rf : constant Node_Id := Compare_Fixup (R);
542
543          function Is_Same_Subscript (L, R : List_Id) return Boolean;
544          --  L, R are the Expressions values from two attribute nodes
545          --  for First or Last attributes. Either may be set to No_List
546          --  if no expressions are present (indicating subscript 1).
547          --  The result is True if both expressions represent the same
548          --  subscript (note that one case is where one subscript is
549          --  missing and the other is explicitly set to 1).
550
551          -----------------------
552          -- Is_Same_Subscript --
553          -----------------------
554
555          function Is_Same_Subscript (L, R : List_Id) return Boolean is
556          begin
557             if L = No_List then
558                if R = No_List then
559                   return True;
560                else
561                   return Expr_Value (First (R)) = Uint_1;
562                end if;
563
564             else
565                if R = No_List then
566                   return Expr_Value (First (L)) = Uint_1;
567                else
568                   return Expr_Value (First (L)) = Expr_Value (First (R));
569                end if;
570             end if;
571          end Is_Same_Subscript;
572
573       --  Start of processing for Is_Same_Value
574
575       begin
576          --  Values are the same if they refer to the same entity and the
577          --  entity is non-volatile. This does not however apply to Float
578          --  types, since we may have two NaN values and they should never
579          --  compare equal.
580
581          if Nkind_In (Lf, N_Identifier, N_Expanded_Name)
582            and then Nkind_In (Rf, N_Identifier, N_Expanded_Name)
583            and then Entity (Lf) = Entity (Rf)
584            and then Present (Entity (Lf))
585            and then not Is_Floating_Point_Type (Etype (L))
586            and then not Is_Volatile_Reference (L)
587            and then not Is_Volatile_Reference (R)
588          then
589             return True;
590
591          --  Or if they are compile time known and identical
592
593          elsif Compile_Time_Known_Value (Lf)
594                  and then
595                Compile_Time_Known_Value (Rf)
596            and then Expr_Value (Lf) = Expr_Value (Rf)
597          then
598             return True;
599
600          --  False if Nkind of the two nodes is different for remaining cases
601
602          elsif Nkind (Lf) /= Nkind (Rf) then
603             return False;
604
605          --  True if both 'First or 'Last values applying to the same entity
606          --  (first and last don't change even if value does). Note that we
607          --  need this even with the calls to Compare_Fixup, to handle the
608          --  case of unconstrained array attributes where Compare_Fixup
609          --  cannot find useful bounds.
610
611          elsif Nkind (Lf) = N_Attribute_Reference
612            and then Attribute_Name (Lf) = Attribute_Name (Rf)
613            and then (Attribute_Name (Lf) = Name_First
614                        or else
615                      Attribute_Name (Lf) = Name_Last)
616            and then Nkind_In (Prefix (Lf), N_Identifier, N_Expanded_Name)
617            and then Nkind_In (Prefix (Rf), N_Identifier, N_Expanded_Name)
618            and then Entity (Prefix (Lf)) = Entity (Prefix (Rf))
619            and then Is_Same_Subscript (Expressions (Lf), Expressions (Rf))
620          then
621             return True;
622
623          --  True if the same selected component from the same record
624
625          elsif Nkind (Lf) = N_Selected_Component
626            and then Selector_Name (Lf) = Selector_Name (Rf)
627            and then Is_Same_Value (Prefix (Lf), Prefix (Rf))
628          then
629             return True;
630
631          --  True if the same unary operator applied to the same operand
632
633          elsif Nkind (Lf) in N_Unary_Op
634            and then Is_Same_Value (Right_Opnd (Lf), Right_Opnd (Rf))
635          then
636             return True;
637
638          --  True if the same binary operator applied to the same operands
639
640          elsif Nkind (Lf) in N_Binary_Op
641            and then Is_Same_Value (Left_Opnd  (Lf), Left_Opnd  (Rf))
642            and then Is_Same_Value (Right_Opnd (Lf), Right_Opnd (Rf))
643          then
644             return True;
645
646          --  All other cases, we can't tell, so return False
647
648          else
649             return False;
650          end if;
651       end Is_Same_Value;
652
653    --  Start of processing for Compile_Time_Compare
654
655    begin
656       --  If either operand could raise constraint error, then we cannot
657       --  know the result at compile time (since CE may be raised!)
658
659       if not (Cannot_Raise_Constraint_Error (L)
660                 and then
661               Cannot_Raise_Constraint_Error (R))
662       then
663          return Unknown;
664       end if;
665
666       --  Identical operands are most certainly equal
667
668       if L = R then
669          return EQ;
670
671       --  If expressions have no types, then do not attempt to determine
672       --  if they are the same, since something funny is going on. One
673       --  case in which this happens is during generic template analysis,
674       --  when bounds are not fully analyzed.
675
676       elsif No (Ltyp) or else No (Rtyp) then
677          return Unknown;
678
679       --  We only attempt compile time analysis for scalar values, and
680       --  not for packed arrays represented as modular types, where the
681       --  semantics of comparison is quite different.
682
683       elsif not Is_Scalar_Type (Ltyp)
684         or else Is_Packed_Array_Type (Ltyp)
685       then
686          return Unknown;
687
688       --  Case where comparison involves two compile time known values
689
690       elsif Compile_Time_Known_Value (L)
691         and then Compile_Time_Known_Value (R)
692       then
693          --  For the floating-point case, we have to be a little careful, since
694          --  at compile time we are dealing with universal exact values, but at
695          --  runtime, these will be in non-exact target form. That's why the
696          --  returned results are LE and GE below instead of LT and GT.
697
698          if Is_Floating_Point_Type (Ltyp)
699               or else
700             Is_Floating_Point_Type (Rtyp)
701          then
702             declare
703                Lo : constant Ureal := Expr_Value_R (L);
704                Hi : constant Ureal := Expr_Value_R (R);
705
706             begin
707                if Lo < Hi then
708                   return LE;
709                elsif Lo = Hi then
710                   return EQ;
711                else
712                   return GE;
713                end if;
714             end;
715
716          --  For the integer case we know exactly (note that this includes the
717          --  fixed-point case, where we know the run time integer values now)
718
719          else
720             declare
721                Lo : constant Uint := Expr_Value (L);
722                Hi : constant Uint := Expr_Value (R);
723
724             begin
725                if Lo < Hi then
726                   return LT;
727                elsif Lo = Hi then
728                   return EQ;
729                else
730                   return GT;
731                end if;
732             end;
733          end if;
734
735       --  Cases where at least one operand is not known at compile time
736
737       else
738          --  Remaining checks apply only for non-generic discrete types
739
740          if not Is_Discrete_Type (Ltyp)
741            or else not Is_Discrete_Type (Rtyp)
742            or else Is_Generic_Type (Ltyp)
743            or else Is_Generic_Type (Rtyp)
744          then
745             return Unknown;
746          end if;
747
748          --  Replace types by base types for the case of entities which are
749          --  not known to have valid representations. This takes care of
750          --  properly dealing with invalid representations.
751
752          if not Assume_Valid and then not Assume_No_Invalid_Values then
753             if Is_Entity_Name (L) and then not Is_Known_Valid (Entity (L)) then
754                Ltyp := Base_Type (Ltyp);
755             end if;
756
757             if Is_Entity_Name (R) and then not Is_Known_Valid (Entity (R)) then
758                Rtyp := Base_Type (Rtyp);
759             end if;
760          end if;
761
762          --  Try range analysis on variables and see if ranges are disjoint
763
764          declare
765             LOK, ROK : Boolean;
766             LLo, LHi : Uint;
767             RLo, RHi : Uint;
768
769          begin
770             Determine_Range (L, LOK, LLo, LHi, Assume_Valid);
771             Determine_Range (R, ROK, RLo, RHi, Assume_Valid);
772
773             if LOK and ROK then
774                if LHi < RLo then
775                   return LT;
776
777                elsif RHi < LLo then
778                   return GT;
779
780                elsif LLo = LHi
781                  and then RLo = RHi
782                  and then LLo = RLo
783                then
784                   return EQ;
785
786                elsif LHi = RLo then
787                   return LE;
788
789                elsif RHi = LLo then
790                   return GE;
791                end if;
792             end if;
793          end;
794
795          --  Here is where we check for comparisons against maximum bounds of
796          --  types, where we know that no value can be outside the bounds of
797          --  the subtype. Note that this routine is allowed to assume that all
798          --  expressions are within their subtype bounds. Callers wishing to
799          --  deal with possibly invalid values must in any case take special
800          --  steps (e.g. conversions to larger types) to avoid this kind of
801          --  optimization, which is always considered to be valid. We do not
802          --  attempt this optimization with generic types, since the type
803          --  bounds may not be meaningful in this case.
804
805          --  We are in danger of an  infinite recursion here. It does not seem
806          --  useful to go more than one level deep, so the parameter Rec is
807          --  used to protect ourselves against this infinite recursion.
808
809          if not Rec then
810
811             --  See if we can get a decisive check against one operand and
812             --  a bound of the other operand (four possible tests here).
813
814             case Compile_Time_Compare (L, Type_Low_Bound (Rtyp),
815                                        Assume_Valid, Rec => True) is
816                when LT => return LT;
817                when LE => return LE;
818                when EQ => return LE;
819                when others => null;
820             end case;
821
822             case Compile_Time_Compare (L, Type_High_Bound (Rtyp),
823                                        Assume_Valid, Rec => True) is
824                when GT => return GT;
825                when GE => return GE;
826                when EQ => return GE;
827                when others => null;
828             end case;
829
830             case Compile_Time_Compare (Type_Low_Bound (Ltyp), R,
831                                        Assume_Valid, Rec => True) is
832                when GT => return GT;
833                when GE => return GE;
834                when EQ => return GE;
835                when others => null;
836             end case;
837
838             case Compile_Time_Compare (Type_High_Bound (Ltyp), R,
839                                        Assume_Valid, Rec => True) is
840                when LT => return LT;
841                when LE => return LE;
842                when EQ => return LE;
843                when others => null;
844             end case;
845          end if;
846
847          --  Next attempt is to decompose the expressions to extract
848          --  a constant offset resulting from the use of any of the forms:
849
850          --     expr + literal
851          --     expr - literal
852          --     typ'Succ (expr)
853          --     typ'Pred (expr)
854
855          --  Then we see if the two expressions are the same value, and if so
856          --  the result is obtained by comparing the offsets.
857
858          declare
859             Lnode : Node_Id;
860             Loffs : Uint;
861             Rnode : Node_Id;
862             Roffs : Uint;
863
864          begin
865             Compare_Decompose (L, Lnode, Loffs);
866             Compare_Decompose (R, Rnode, Roffs);
867
868             if Is_Same_Value (Lnode, Rnode) then
869                if Loffs = Roffs then
870                   return EQ;
871
872                elsif Loffs < Roffs then
873                   return LT;
874
875                else
876                   return GT;
877                end if;
878             end if;
879          end;
880
881          --  Next attempt is to see if we have an entity compared with a
882          --  compile time known value, where there is a current value
883          --  conditional for the entity which can tell us the result.
884
885          declare
886             Var : Node_Id;
887             --  Entity variable (left operand)
888
889             Val : Uint;
890             --  Value (right operand)
891
892             Inv : Boolean;
893             --  If False, we have reversed the operands
894
895             Op : Node_Kind;
896             --  Comparison operator kind from Get_Current_Value_Condition call
897
898             Opn : Node_Id;
899             --  Value from Get_Current_Value_Condition call
900
901             Opv : Uint;
902             --  Value of Opn
903
904             Result : Compare_Result;
905             --  Known result before inversion
906
907          begin
908             if Is_Entity_Name (L)
909               and then Compile_Time_Known_Value (R)
910             then
911                Var := L;
912                Val := Expr_Value (R);
913                Inv := False;
914
915             elsif Is_Entity_Name (R)
916               and then Compile_Time_Known_Value (L)
917             then
918                Var := R;
919                Val := Expr_Value (L);
920                Inv := True;
921
922                --  That was the last chance at finding a compile time result
923
924             else
925                return Unknown;
926             end if;
927
928             Get_Current_Value_Condition (Var, Op, Opn);
929
930             --  That was the last chance, so if we got nothing return
931
932             if No (Opn) then
933                return Unknown;
934             end if;
935
936             Opv := Expr_Value (Opn);
937
938             --  We got a comparison, so we might have something interesting
939
940             --  Convert LE to LT and GE to GT, just so we have fewer cases
941
942             if Op = N_Op_Le then
943                Op := N_Op_Lt;
944                Opv := Opv + 1;
945             elsif Op = N_Op_Ge then
946                Op := N_Op_Gt;
947                Opv := Opv - 1;
948             end if;
949
950             --  Deal with equality case
951
952             if Op = N_Op_Eq then
953                if Val = Opv then
954                   Result := EQ;
955                elsif Opv < Val then
956                   Result := LT;
957                else
958                   Result := GT;
959                end if;
960
961             --  Deal with inequality case
962
963             elsif Op = N_Op_Ne then
964                if Val = Opv then
965                   Result := NE;
966                else
967                   return Unknown;
968                end if;
969
970             --  Deal with greater than case
971
972             elsif Op = N_Op_Gt then
973                if Opv >= Val then
974                   Result := GT;
975                elsif Opv = Val - 1 then
976                   Result := GE;
977                else
978                   return Unknown;
979                end if;
980
981             --  Deal with less than case
982
983             else pragma Assert (Op = N_Op_Lt);
984                if Opv <= Val then
985                   Result := LT;
986                elsif Opv = Val + 1 then
987                   Result := LE;
988                else
989                   return Unknown;
990                end if;
991             end if;
992
993             --  Deal with inverting result
994
995             if Inv then
996                case Result is
997                   when GT     => return LT;
998                   when GE     => return LE;
999                   when LT     => return GT;
1000                   when LE     => return GE;
1001                   when others => return Result;
1002                end case;
1003             end if;
1004
1005             return Result;
1006          end;
1007       end if;
1008    end Compile_Time_Compare;
1009
1010    -------------------------------
1011    -- Compile_Time_Known_Bounds --
1012    -------------------------------
1013
1014    function Compile_Time_Known_Bounds (T : Entity_Id) return Boolean is
1015       Indx : Node_Id;
1016       Typ  : Entity_Id;
1017
1018    begin
1019       if not Is_Array_Type (T) then
1020          return False;
1021       end if;
1022
1023       Indx := First_Index (T);
1024       while Present (Indx) loop
1025          Typ := Underlying_Type (Etype (Indx));
1026          if not Compile_Time_Known_Value (Type_Low_Bound (Typ)) then
1027             return False;
1028          elsif not Compile_Time_Known_Value (Type_High_Bound (Typ)) then
1029             return False;
1030          else
1031             Next_Index (Indx);
1032          end if;
1033       end loop;
1034
1035       return True;
1036    end Compile_Time_Known_Bounds;
1037
1038    ------------------------------
1039    -- Compile_Time_Known_Value --
1040    ------------------------------
1041
1042    function Compile_Time_Known_Value (Op : Node_Id) return Boolean is
1043       K      : constant Node_Kind := Nkind (Op);
1044       CV_Ent : CV_Entry renames CV_Cache (Nat (Op) mod CV_Cache_Size);
1045
1046    begin
1047       --  Never known at compile time if bad type or raises constraint error
1048       --  or empty (latter case occurs only as a result of a previous error)
1049
1050       if No (Op)
1051         or else Op = Error
1052         or else Etype (Op) = Any_Type
1053         or else Raises_Constraint_Error (Op)
1054       then
1055          return False;
1056       end if;
1057
1058       --  If this is not a static expression or a null literal, and we are in
1059       --  configurable run-time mode, then we consider it not known at compile
1060       --  time. This avoids anomalies where whether something is allowed with a
1061       --  given configurable run-time library depends on how good the compiler
1062       --  is at optimizing and knowing that things are constant when they are
1063       --  nonstatic.
1064
1065       if Configurable_Run_Time_Mode
1066         and then K /= N_Null
1067         and then not Is_Static_Expression (Op)
1068       then
1069          return False;
1070       end if;
1071
1072       --  If we have an entity name, then see if it is the name of a constant
1073       --  and if so, test the corresponding constant value, or the name of
1074       --  an enumeration literal, which is always a constant.
1075
1076       if Present (Etype (Op)) and then Is_Entity_Name (Op) then
1077          declare
1078             E : constant Entity_Id := Entity (Op);
1079             V : Node_Id;
1080
1081          begin
1082             --  Never known at compile time if it is a packed array value.
1083             --  We might want to try to evaluate these at compile time one
1084             --  day, but we do not make that attempt now.
1085
1086             if Is_Packed_Array_Type (Etype (Op)) then
1087                return False;
1088             end if;
1089
1090             if Ekind (E) = E_Enumeration_Literal then
1091                return True;
1092
1093             elsif Ekind (E) = E_Constant then
1094                V := Constant_Value (E);
1095                return Present (V) and then Compile_Time_Known_Value (V);
1096             end if;
1097          end;
1098
1099       --  We have a value, see if it is compile time known
1100
1101       else
1102          --  Integer literals are worth storing in the cache
1103
1104          if K = N_Integer_Literal then
1105             CV_Ent.N := Op;
1106             CV_Ent.V := Intval (Op);
1107             return True;
1108
1109          --  Other literals and NULL are known at compile time
1110
1111          elsif
1112             K = N_Character_Literal
1113               or else
1114             K = N_Real_Literal
1115               or else
1116             K = N_String_Literal
1117               or else
1118             K = N_Null
1119          then
1120             return True;
1121
1122          --  Any reference to Null_Parameter is known at compile time. No
1123          --  other attribute references (that have not already been folded)
1124          --  are known at compile time.
1125
1126          elsif K = N_Attribute_Reference then
1127             return Attribute_Name (Op) = Name_Null_Parameter;
1128          end if;
1129       end if;
1130
1131       --  If we fall through, not known at compile time
1132
1133       return False;
1134
1135    --  If we get an exception while trying to do this test, then some error
1136    --  has occurred, and we simply say that the value is not known after all
1137
1138    exception
1139       when others =>
1140          return False;
1141    end Compile_Time_Known_Value;
1142
1143    --------------------------------------
1144    -- Compile_Time_Known_Value_Or_Aggr --
1145    --------------------------------------
1146
1147    function Compile_Time_Known_Value_Or_Aggr (Op : Node_Id) return Boolean is
1148    begin
1149       --  If we have an entity name, then see if it is the name of a constant
1150       --  and if so, test the corresponding constant value, or the name of
1151       --  an enumeration literal, which is always a constant.
1152
1153       if Is_Entity_Name (Op) then
1154          declare
1155             E : constant Entity_Id := Entity (Op);
1156             V : Node_Id;
1157
1158          begin
1159             if Ekind (E) = E_Enumeration_Literal then
1160                return True;
1161
1162             elsif Ekind (E) /= E_Constant then
1163                return False;
1164
1165             else
1166                V := Constant_Value (E);
1167                return Present (V)
1168                  and then Compile_Time_Known_Value_Or_Aggr (V);
1169             end if;
1170          end;
1171
1172       --  We have a value, see if it is compile time known
1173
1174       else
1175          if Compile_Time_Known_Value (Op) then
1176             return True;
1177
1178          elsif Nkind (Op) = N_Aggregate then
1179
1180             if Present (Expressions (Op)) then
1181                declare
1182                   Expr : Node_Id;
1183
1184                begin
1185                   Expr := First (Expressions (Op));
1186                   while Present (Expr) loop
1187                      if not Compile_Time_Known_Value_Or_Aggr (Expr) then
1188                         return False;
1189                      end if;
1190
1191                      Next (Expr);
1192                   end loop;
1193                end;
1194             end if;
1195
1196             if Present (Component_Associations (Op)) then
1197                declare
1198                   Cass : Node_Id;
1199
1200                begin
1201                   Cass := First (Component_Associations (Op));
1202                   while Present (Cass) loop
1203                      if not
1204                        Compile_Time_Known_Value_Or_Aggr (Expression (Cass))
1205                      then
1206                         return False;
1207                      end if;
1208
1209                      Next (Cass);
1210                   end loop;
1211                end;
1212             end if;
1213
1214             return True;
1215
1216          --  All other types of values are not known at compile time
1217
1218          else
1219             return False;
1220          end if;
1221
1222       end if;
1223    end Compile_Time_Known_Value_Or_Aggr;
1224
1225    -----------------
1226    -- Eval_Actual --
1227    -----------------
1228
1229    --  This is only called for actuals of functions that are not predefined
1230    --  operators (which have already been rewritten as operators at this
1231    --  stage), so the call can never be folded, and all that needs doing for
1232    --  the actual is to do the check for a non-static context.
1233
1234    procedure Eval_Actual (N : Node_Id) is
1235    begin
1236       Check_Non_Static_Context (N);
1237    end Eval_Actual;
1238
1239    --------------------
1240    -- Eval_Allocator --
1241    --------------------
1242
1243    --  Allocators are never static, so all we have to do is to do the
1244    --  check for a non-static context if an expression is present.
1245
1246    procedure Eval_Allocator (N : Node_Id) is
1247       Expr : constant Node_Id := Expression (N);
1248
1249    begin
1250       if Nkind (Expr) = N_Qualified_Expression then
1251          Check_Non_Static_Context (Expression (Expr));
1252       end if;
1253    end Eval_Allocator;
1254
1255    ------------------------
1256    -- Eval_Arithmetic_Op --
1257    ------------------------
1258
1259    --  Arithmetic operations are static functions, so the result is static
1260    --  if both operands are static (RM 4.9(7), 4.9(20)).
1261
1262    procedure Eval_Arithmetic_Op (N : Node_Id) is
1263       Left  : constant Node_Id   := Left_Opnd (N);
1264       Right : constant Node_Id   := Right_Opnd (N);
1265       Ltype : constant Entity_Id := Etype (Left);
1266       Rtype : constant Entity_Id := Etype (Right);
1267       Stat  : Boolean;
1268       Fold  : Boolean;
1269
1270    begin
1271       --  If not foldable we are done
1272
1273       Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold);
1274
1275       if not Fold then
1276          return;
1277       end if;
1278
1279       --  Fold for cases where both operands are of integer type
1280
1281       if Is_Integer_Type (Ltype) and then Is_Integer_Type (Rtype) then
1282          declare
1283             Left_Int  : constant Uint := Expr_Value (Left);
1284             Right_Int : constant Uint := Expr_Value (Right);
1285             Result    : Uint;
1286
1287          begin
1288             case Nkind (N) is
1289
1290                when N_Op_Add =>
1291                   Result := Left_Int + Right_Int;
1292
1293                when N_Op_Subtract =>
1294                   Result := Left_Int - Right_Int;
1295
1296                when N_Op_Multiply =>
1297                   if OK_Bits
1298                        (N, UI_From_Int
1299                              (Num_Bits (Left_Int) + Num_Bits (Right_Int)))
1300                   then
1301                      Result := Left_Int * Right_Int;
1302                   else
1303                      Result := Left_Int;
1304                   end if;
1305
1306                when N_Op_Divide =>
1307
1308                   --  The exception Constraint_Error is raised by integer
1309                   --  division, rem and mod if the right operand is zero.
1310
1311                   if Right_Int = 0 then
1312                      Apply_Compile_Time_Constraint_Error
1313                        (N, "division by zero",
1314                         CE_Divide_By_Zero,
1315                         Warn => not Stat);
1316                      return;
1317
1318                   else
1319                      Result := Left_Int / Right_Int;
1320                   end if;
1321
1322                when N_Op_Mod =>
1323
1324                   --  The exception Constraint_Error is raised by integer
1325                   --  division, rem and mod if the right operand is zero.
1326
1327                   if Right_Int = 0 then
1328                      Apply_Compile_Time_Constraint_Error
1329                        (N, "mod with zero divisor",
1330                         CE_Divide_By_Zero,
1331                         Warn => not Stat);
1332                      return;
1333                   else
1334                      Result := Left_Int mod Right_Int;
1335                   end if;
1336
1337                when N_Op_Rem =>
1338
1339                   --  The exception Constraint_Error is raised by integer
1340                   --  division, rem and mod if the right operand is zero.
1341
1342                   if Right_Int = 0 then
1343                      Apply_Compile_Time_Constraint_Error
1344                        (N, "rem with zero divisor",
1345                         CE_Divide_By_Zero,
1346                         Warn => not Stat);
1347                      return;
1348
1349                   else
1350                      Result := Left_Int rem Right_Int;
1351                   end if;
1352
1353                when others =>
1354                   raise Program_Error;
1355             end case;
1356
1357             --  Adjust the result by the modulus if the type is a modular type
1358
1359             if Is_Modular_Integer_Type (Ltype) then
1360                Result := Result mod Modulus (Ltype);
1361
1362                --  For a signed integer type, check non-static overflow
1363
1364             elsif (not Stat) and then Is_Signed_Integer_Type (Ltype) then
1365                declare
1366                   BT : constant Entity_Id := Base_Type (Ltype);
1367                   Lo : constant Uint := Expr_Value (Type_Low_Bound (BT));
1368                   Hi : constant Uint := Expr_Value (Type_High_Bound (BT));
1369                begin
1370                   if Result < Lo or else Result > Hi then
1371                      Apply_Compile_Time_Constraint_Error
1372                        (N, "value not in range of }?",
1373                         CE_Overflow_Check_Failed,
1374                         Ent => BT);
1375                      return;
1376                   end if;
1377                end;
1378             end if;
1379
1380             --  If we get here we can fold the result
1381
1382             Fold_Uint (N, Result, Stat);
1383          end;
1384
1385       --  Cases where at least one operand is a real. We handle the cases
1386       --  of both reals, or mixed/real integer cases (the latter happen
1387       --  only for divide and multiply, and the result is always real).
1388
1389       elsif Is_Real_Type (Ltype) or else Is_Real_Type (Rtype) then
1390          declare
1391             Left_Real  : Ureal;
1392             Right_Real : Ureal;
1393             Result     : Ureal;
1394
1395          begin
1396             if Is_Real_Type (Ltype) then
1397                Left_Real := Expr_Value_R (Left);
1398             else
1399                Left_Real := UR_From_Uint (Expr_Value (Left));
1400             end if;
1401
1402             if Is_Real_Type (Rtype) then
1403                Right_Real := Expr_Value_R (Right);
1404             else
1405                Right_Real := UR_From_Uint (Expr_Value (Right));
1406             end if;
1407
1408             if Nkind (N) = N_Op_Add then
1409                Result := Left_Real + Right_Real;
1410
1411             elsif Nkind (N) = N_Op_Subtract then
1412                Result := Left_Real - Right_Real;
1413
1414             elsif Nkind (N) = N_Op_Multiply then
1415                Result := Left_Real * Right_Real;
1416
1417             else pragma Assert (Nkind (N) = N_Op_Divide);
1418                if UR_Is_Zero (Right_Real) then
1419                   Apply_Compile_Time_Constraint_Error
1420                     (N, "division by zero", CE_Divide_By_Zero);
1421                   return;
1422                end if;
1423
1424                Result := Left_Real / Right_Real;
1425             end if;
1426
1427             Fold_Ureal (N, Result, Stat);
1428          end;
1429       end if;
1430    end Eval_Arithmetic_Op;
1431
1432    ----------------------------
1433    -- Eval_Character_Literal --
1434    ----------------------------
1435
1436    --  Nothing to be done!
1437
1438    procedure Eval_Character_Literal (N : Node_Id) is
1439       pragma Warnings (Off, N);
1440    begin
1441       null;
1442    end Eval_Character_Literal;
1443
1444    ---------------
1445    -- Eval_Call --
1446    ---------------
1447
1448    --  Static function calls are either calls to predefined operators
1449    --  with static arguments, or calls to functions that rename a literal.
1450    --  Only the latter case is handled here, predefined operators are
1451    --  constant-folded elsewhere.
1452
1453    --  If the function is itself inherited (see 7423-001) the literal of
1454    --  the parent type must be explicitly converted to the return type
1455    --  of the function.
1456
1457    procedure Eval_Call (N : Node_Id) is
1458       Loc : constant Source_Ptr := Sloc (N);
1459       Typ : constant Entity_Id  := Etype (N);
1460       Lit : Entity_Id;
1461
1462    begin
1463       if Nkind (N) = N_Function_Call
1464         and then No (Parameter_Associations (N))
1465         and then Is_Entity_Name (Name (N))
1466         and then Present (Alias (Entity (Name (N))))
1467         and then Is_Enumeration_Type (Base_Type (Typ))
1468       then
1469          Lit := Alias (Entity (Name (N)));
1470          while Present (Alias (Lit)) loop
1471             Lit := Alias (Lit);
1472          end loop;
1473
1474          if Ekind (Lit) = E_Enumeration_Literal then
1475             if Base_Type (Etype (Lit)) /= Base_Type (Typ) then
1476                Rewrite
1477                  (N, Convert_To (Typ, New_Occurrence_Of (Lit, Loc)));
1478             else
1479                Rewrite (N, New_Occurrence_Of (Lit, Loc));
1480             end if;
1481
1482             Resolve (N, Typ);
1483          end if;
1484       end if;
1485    end Eval_Call;
1486
1487    ------------------------
1488    -- Eval_Concatenation --
1489    ------------------------
1490
1491    --  Concatenation is a static function, so the result is static if
1492    --  both operands are static (RM 4.9(7), 4.9(21)).
1493
1494    procedure Eval_Concatenation (N : Node_Id) is
1495       Left  : constant Node_Id   := Left_Opnd (N);
1496       Right : constant Node_Id   := Right_Opnd (N);
1497       C_Typ : constant Entity_Id := Root_Type (Component_Type (Etype (N)));
1498       Stat  : Boolean;
1499       Fold  : Boolean;
1500
1501    begin
1502       --  Concatenation is never static in Ada 83, so if Ada 83
1503       --  check operand non-static context
1504
1505       if Ada_Version = Ada_83
1506         and then Comes_From_Source (N)
1507       then
1508          Check_Non_Static_Context (Left);
1509          Check_Non_Static_Context (Right);
1510          return;
1511       end if;
1512
1513       --  If not foldable we are done. In principle concatenation that yields
1514       --  any string type is static (i.e. an array type of character types).
1515       --  However, character types can include enumeration literals, and
1516       --  concatenation in that case cannot be described by a literal, so we
1517       --  only consider the operation static if the result is an array of
1518       --  (a descendant of) a predefined character type.
1519
1520       Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold);
1521
1522       if Is_Standard_Character_Type (C_Typ)
1523         and then Fold
1524       then
1525          null;
1526       else
1527          Set_Is_Static_Expression (N, False);
1528          return;
1529       end if;
1530
1531       --  Compile time string concatenation
1532
1533       --  ??? Note that operands that are aggregates can be marked as
1534       --  static, so we should attempt at a later stage to fold
1535       --  concatenations with such aggregates.
1536
1537       declare
1538          Left_Str   : constant Node_Id := Get_String_Val (Left);
1539          Left_Len   : Nat;
1540          Right_Str  : constant Node_Id := Get_String_Val (Right);
1541          Folded_Val : String_Id;
1542
1543       begin
1544          --  Establish new string literal, and store left operand. We make
1545          --  sure to use the special Start_String that takes an operand if
1546          --  the left operand is a string literal. Since this is optimized
1547          --  in the case where that is the most recently created string
1548          --  literal, we ensure efficient time/space behavior for the
1549          --  case of a concatenation of a series of string literals.
1550
1551          if Nkind (Left_Str) = N_String_Literal then
1552             Left_Len :=  String_Length (Strval (Left_Str));
1553
1554             --  If the left operand is the empty string, and the right operand
1555             --  is a string literal (the case of "" & "..."), the result is the
1556             --  value of the right operand. This optimization is important when
1557             --  Is_Folded_In_Parser, to avoid copying an enormous right
1558             --  operand.
1559
1560             if Left_Len = 0 and then Nkind (Right_Str) = N_String_Literal then
1561                Folded_Val := Strval (Right_Str);
1562             else
1563                Start_String (Strval (Left_Str));
1564             end if;
1565
1566          else
1567             Start_String;
1568             Store_String_Char (UI_To_CC (Char_Literal_Value (Left_Str)));
1569             Left_Len := 1;
1570          end if;
1571
1572          --  Now append the characters of the right operand, unless we
1573          --  optimized the "" & "..." case above.
1574
1575          if Nkind (Right_Str) = N_String_Literal then
1576             if Left_Len /= 0 then
1577                Store_String_Chars (Strval (Right_Str));
1578                Folded_Val := End_String;
1579             end if;
1580          else
1581             Store_String_Char (UI_To_CC (Char_Literal_Value (Right_Str)));
1582             Folded_Val := End_String;
1583          end if;
1584
1585          Set_Is_Static_Expression (N, Stat);
1586
1587          if Stat then
1588
1589             --  If left operand is the empty string, the result is the
1590             --  right operand, including its bounds if anomalous.
1591
1592             if Left_Len = 0
1593               and then Is_Array_Type (Etype (Right))
1594               and then Etype (Right) /= Any_String
1595             then
1596                Set_Etype (N, Etype (Right));
1597             end if;
1598
1599             Fold_Str (N, Folded_Val, Static => True);
1600          end if;
1601       end;
1602    end Eval_Concatenation;
1603
1604    ---------------------------------
1605    -- Eval_Conditional_Expression --
1606    ---------------------------------
1607
1608    --  This GNAT internal construct can never be statically folded, so the
1609    --  only required processing is to do the check for non-static context
1610    --  for the two expression operands.
1611
1612    procedure Eval_Conditional_Expression (N : Node_Id) is
1613       Condition : constant Node_Id := First (Expressions (N));
1614       Then_Expr : constant Node_Id := Next (Condition);
1615       Else_Expr : constant Node_Id := Next (Then_Expr);
1616
1617    begin
1618       Check_Non_Static_Context (Then_Expr);
1619       Check_Non_Static_Context (Else_Expr);
1620    end Eval_Conditional_Expression;
1621
1622    ----------------------
1623    -- Eval_Entity_Name --
1624    ----------------------
1625
1626    --  This procedure is used for identifiers and expanded names other than
1627    --  named numbers (see Eval_Named_Integer, Eval_Named_Real. These are
1628    --  static if they denote a static constant (RM 4.9(6)) or if the name
1629    --  denotes an enumeration literal (RM 4.9(22)).
1630
1631    procedure Eval_Entity_Name (N : Node_Id) is
1632       Def_Id : constant Entity_Id := Entity (N);
1633       Val    : Node_Id;
1634
1635    begin
1636       --  Enumeration literals are always considered to be constants
1637       --  and cannot raise constraint error (RM 4.9(22)).
1638
1639       if Ekind (Def_Id) = E_Enumeration_Literal then
1640          Set_Is_Static_Expression (N);
1641          return;
1642
1643       --  A name is static if it denotes a static constant (RM 4.9(5)), and
1644       --  we also copy Raise_Constraint_Error. Notice that even if non-static,
1645       --  it does not violate 10.2.1(8) here, since this is not a variable.
1646
1647       elsif Ekind (Def_Id) = E_Constant then
1648
1649          --  Deferred constants must always be treated as nonstatic
1650          --  outside the scope of their full view.
1651
1652          if Present (Full_View (Def_Id))
1653            and then not In_Open_Scopes (Scope (Def_Id))
1654          then
1655             Val := Empty;
1656          else
1657             Val := Constant_Value (Def_Id);
1658          end if;
1659
1660          if Present (Val) then
1661             Set_Is_Static_Expression
1662               (N, Is_Static_Expression (Val)
1663                     and then Is_Static_Subtype (Etype (Def_Id)));
1664             Set_Raises_Constraint_Error (N, Raises_Constraint_Error (Val));
1665
1666             if not Is_Static_Expression (N)
1667               and then not Is_Generic_Type (Etype (N))
1668             then
1669                Validate_Static_Object_Name (N);
1670             end if;
1671
1672             return;
1673          end if;
1674       end if;
1675
1676       --  Fall through if the name is not static
1677
1678       Validate_Static_Object_Name (N);
1679    end Eval_Entity_Name;
1680
1681    ----------------------------
1682    -- Eval_Indexed_Component --
1683    ----------------------------
1684
1685    --  Indexed components are never static, so we need to perform the check
1686    --  for non-static context on the index values. Then, we check if the
1687    --  value can be obtained at compile time, even though it is non-static.
1688
1689    procedure Eval_Indexed_Component (N : Node_Id) is
1690       Expr : Node_Id;
1691
1692    begin
1693       --  Check for non-static context on index values
1694
1695       Expr := First (Expressions (N));
1696       while Present (Expr) loop
1697          Check_Non_Static_Context (Expr);
1698          Next (Expr);
1699       end loop;
1700
1701       --  If the indexed component appears in an object renaming declaration
1702       --  then we do not want to try to evaluate it, since in this case we
1703       --  need the identity of the array element.
1704
1705       if Nkind (Parent (N)) = N_Object_Renaming_Declaration then
1706          return;
1707
1708       --  Similarly if the indexed component appears as the prefix of an
1709       --  attribute we don't want to evaluate it, because at least for
1710       --  some cases of attributes we need the identify (e.g. Access, Size)
1711
1712       elsif Nkind (Parent (N)) = N_Attribute_Reference then
1713          return;
1714       end if;
1715
1716       --  Note: there are other cases, such as the left side of an assignment,
1717       --  or an OUT parameter for a call, where the replacement results in the
1718       --  illegal use of a constant, But these cases are illegal in the first
1719       --  place, so the replacement, though silly, is harmless.
1720
1721       --  Now see if this is a constant array reference
1722
1723       if List_Length (Expressions (N)) = 1
1724         and then Is_Entity_Name (Prefix (N))
1725         and then Ekind (Entity (Prefix (N))) = E_Constant
1726         and then Present (Constant_Value (Entity (Prefix (N))))
1727       then
1728          declare
1729             Loc : constant Source_Ptr := Sloc (N);
1730             Arr : constant Node_Id    := Constant_Value (Entity (Prefix (N)));
1731             Sub : constant Node_Id    := First (Expressions (N));
1732
1733             Atyp : Entity_Id;
1734             --  Type of array
1735
1736             Lin : Nat;
1737             --  Linear one's origin subscript value for array reference
1738
1739             Lbd : Node_Id;
1740             --  Lower bound of the first array index
1741
1742             Elm : Node_Id;
1743             --  Value from constant array
1744
1745          begin
1746             Atyp := Etype (Arr);
1747
1748             if Is_Access_Type (Atyp) then
1749                Atyp := Designated_Type (Atyp);
1750             end if;
1751
1752             --  If we have an array type (we should have but perhaps there
1753             --  are error cases where this is not the case), then see if we
1754             --  can do a constant evaluation of the array reference.
1755
1756             if Is_Array_Type (Atyp) then
1757                if Ekind (Atyp) = E_String_Literal_Subtype then
1758                   Lbd := String_Literal_Low_Bound (Atyp);
1759                else
1760                   Lbd := Type_Low_Bound (Etype (First_Index (Atyp)));
1761                end if;
1762
1763                if Compile_Time_Known_Value (Sub)
1764                  and then Nkind (Arr) = N_Aggregate
1765                  and then Compile_Time_Known_Value (Lbd)
1766                  and then Is_Discrete_Type (Component_Type (Atyp))
1767                then
1768                   Lin := UI_To_Int (Expr_Value (Sub) - Expr_Value (Lbd)) + 1;
1769
1770                   if List_Length (Expressions (Arr)) >= Lin then
1771                      Elm := Pick (Expressions (Arr), Lin);
1772
1773                      --  If the resulting expression is compile time known,
1774                      --  then we can rewrite the indexed component with this
1775                      --  value, being sure to mark the result as non-static.
1776                      --  We also reset the Sloc, in case this generates an
1777                      --  error later on (e.g. 136'Access).
1778
1779                      if Compile_Time_Known_Value (Elm) then
1780                         Rewrite (N, Duplicate_Subexpr_No_Checks (Elm));
1781                         Set_Is_Static_Expression (N, False);
1782                         Set_Sloc (N, Loc);
1783                      end if;
1784                   end if;
1785                end if;
1786             end if;
1787          end;
1788       end if;
1789    end Eval_Indexed_Component;
1790
1791    --------------------------
1792    -- Eval_Integer_Literal --
1793    --------------------------
1794
1795    --  Numeric literals are static (RM 4.9(1)), and have already been marked
1796    --  as static by the analyzer. The reason we did it that early is to allow
1797    --  the possibility of turning off the Is_Static_Expression flag after
1798    --  analysis, but before resolution, when integer literals are generated
1799    --  in the expander that do not correspond to static expressions.
1800
1801    procedure Eval_Integer_Literal (N : Node_Id) is
1802       T : constant Entity_Id := Etype (N);
1803
1804       function In_Any_Integer_Context return Boolean;
1805       --  If the literal is resolved with a specific type in a context
1806       --  where the expected type is Any_Integer, there are no range checks
1807       --  on the literal. By the time the literal is evaluated, it carries
1808       --  the type imposed by the enclosing expression, and we must recover
1809       --  the context to determine that Any_Integer is meant.
1810
1811       ----------------------------
1812       -- To_Any_Integer_Context --
1813       ----------------------------
1814
1815       function In_Any_Integer_Context return Boolean is
1816          Par : constant Node_Id   := Parent (N);
1817          K   : constant Node_Kind := Nkind (Par);
1818
1819       begin
1820          --  Any_Integer also appears in digits specifications for real types,
1821          --  but those have bounds smaller that those of any integer base
1822          --  type, so we can safely ignore these cases.
1823
1824          return    K = N_Number_Declaration
1825            or else K = N_Attribute_Reference
1826            or else K = N_Attribute_Definition_Clause
1827            or else K = N_Modular_Type_Definition
1828            or else K = N_Signed_Integer_Type_Definition;
1829       end In_Any_Integer_Context;
1830
1831    --  Start of processing for Eval_Integer_Literal
1832
1833    begin
1834
1835       --  If the literal appears in a non-expression context, then it is
1836       --  certainly appearing in a non-static context, so check it. This
1837       --  is actually a redundant check, since Check_Non_Static_Context
1838       --  would check it, but it seems worth while avoiding the call.
1839
1840       if Nkind (Parent (N)) not in N_Subexpr
1841         and then not In_Any_Integer_Context
1842       then
1843          Check_Non_Static_Context (N);
1844       end if;
1845
1846       --  Modular integer literals must be in their base range
1847
1848       if Is_Modular_Integer_Type (T)
1849         and then Is_Out_Of_Range (N, Base_Type (T), Assume_Valid => True)
1850       then
1851          Out_Of_Range (N);
1852       end if;
1853    end Eval_Integer_Literal;
1854
1855    ---------------------
1856    -- Eval_Logical_Op --
1857    ---------------------
1858
1859    --  Logical operations are static functions, so the result is potentially
1860    --  static if both operands are potentially static (RM 4.9(7), 4.9(20)).
1861
1862    procedure Eval_Logical_Op (N : Node_Id) is
1863       Left  : constant Node_Id := Left_Opnd (N);
1864       Right : constant Node_Id := Right_Opnd (N);
1865       Stat  : Boolean;
1866       Fold  : Boolean;
1867
1868    begin
1869       --  If not foldable we are done
1870
1871       Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold);
1872
1873       if not Fold then
1874          return;
1875       end if;
1876
1877       --  Compile time evaluation of logical operation
1878
1879       declare
1880          Left_Int  : constant Uint := Expr_Value (Left);
1881          Right_Int : constant Uint := Expr_Value (Right);
1882
1883       begin
1884          if Is_Modular_Integer_Type (Etype (N)) then
1885             declare
1886                Left_Bits  : Bits (0 .. UI_To_Int (Esize (Etype (N))) - 1);
1887                Right_Bits : Bits (0 .. UI_To_Int (Esize (Etype (N))) - 1);
1888
1889             begin
1890                To_Bits (Left_Int, Left_Bits);
1891                To_Bits (Right_Int, Right_Bits);
1892
1893                --  Note: should really be able to use array ops instead of
1894                --  these loops, but they weren't working at the time ???
1895
1896                if Nkind (N) = N_Op_And then
1897                   for J in Left_Bits'Range loop
1898                      Left_Bits (J) := Left_Bits (J) and Right_Bits (J);
1899                   end loop;
1900
1901                elsif Nkind (N) = N_Op_Or then
1902                   for J in Left_Bits'Range loop
1903                      Left_Bits (J) := Left_Bits (J) or Right_Bits (J);
1904                   end loop;
1905
1906                else
1907                   pragma Assert (Nkind (N) = N_Op_Xor);
1908
1909                   for J in Left_Bits'Range loop
1910                      Left_Bits (J) := Left_Bits (J) xor Right_Bits (J);
1911                   end loop;
1912                end if;
1913
1914                Fold_Uint (N, From_Bits (Left_Bits, Etype (N)), Stat);
1915             end;
1916
1917          else
1918             pragma Assert (Is_Boolean_Type (Etype (N)));
1919
1920             if Nkind (N) = N_Op_And then
1921                Fold_Uint (N,
1922                  Test (Is_True (Left_Int) and then Is_True (Right_Int)), Stat);
1923
1924             elsif Nkind (N) = N_Op_Or then
1925                Fold_Uint (N,
1926                  Test (Is_True (Left_Int) or else Is_True (Right_Int)), Stat);
1927
1928             else
1929                pragma Assert (Nkind (N) = N_Op_Xor);
1930                Fold_Uint (N,
1931                  Test (Is_True (Left_Int) xor Is_True (Right_Int)), Stat);
1932             end if;
1933          end if;
1934       end;
1935    end Eval_Logical_Op;
1936
1937    ------------------------
1938    -- Eval_Membership_Op --
1939    ------------------------
1940
1941    --  A membership test is potentially static if the expression is static,
1942    --  and the range is a potentially static range, or is a subtype mark
1943    --  denoting a static subtype (RM 4.9(12)).
1944
1945    procedure Eval_Membership_Op (N : Node_Id) is
1946       Left   : constant Node_Id := Left_Opnd (N);
1947       Right  : constant Node_Id := Right_Opnd (N);
1948       Def_Id : Entity_Id;
1949       Lo     : Node_Id;
1950       Hi     : Node_Id;
1951       Result : Boolean;
1952       Stat   : Boolean;
1953       Fold   : Boolean;
1954
1955    begin
1956       --  Ignore if error in either operand, except to make sure that
1957       --  Any_Type is properly propagated to avoid junk cascaded errors.
1958
1959       if Etype (Left) = Any_Type
1960         or else Etype (Right) = Any_Type
1961       then
1962          Set_Etype (N, Any_Type);
1963          return;
1964       end if;
1965
1966       --  Case of right operand is a subtype name
1967
1968       if Is_Entity_Name (Right) then
1969          Def_Id := Entity (Right);
1970
1971          if (Is_Scalar_Type (Def_Id) or else Is_String_Type (Def_Id))
1972            and then Is_OK_Static_Subtype (Def_Id)
1973          then
1974             Test_Expression_Is_Foldable (N, Left, Stat, Fold);
1975
1976             if not Fold or else not Stat then
1977                return;
1978             end if;
1979          else
1980             Check_Non_Static_Context (Left);
1981             return;
1982          end if;
1983
1984          --  For string membership tests we will check the length
1985          --  further below.
1986
1987          if not Is_String_Type (Def_Id) then
1988             Lo := Type_Low_Bound (Def_Id);
1989             Hi := Type_High_Bound (Def_Id);
1990
1991          else
1992             Lo := Empty;
1993             Hi := Empty;
1994          end if;
1995
1996       --  Case of right operand is a range
1997
1998       else
1999          if Is_Static_Range (Right) then
2000             Test_Expression_Is_Foldable (N, Left, Stat, Fold);
2001
2002             if not Fold or else not Stat then
2003                return;
2004
2005             --  If one bound of range raises CE, then don't try to fold
2006
2007             elsif not Is_OK_Static_Range (Right) then
2008                Check_Non_Static_Context (Left);
2009                return;
2010             end if;
2011
2012          else
2013             Check_Non_Static_Context (Left);
2014             return;
2015          end if;
2016
2017          --  Here we know range is an OK static range
2018
2019          Lo := Low_Bound (Right);
2020          Hi := High_Bound (Right);
2021       end if;
2022
2023       --  For strings we check that the length of the string expression is
2024       --  compatible with the string subtype if the subtype is constrained,
2025       --  or if unconstrained then the test is always true.
2026
2027       if Is_String_Type (Etype (Right)) then
2028          if not Is_Constrained (Etype (Right)) then
2029             Result := True;
2030
2031          else
2032             declare
2033                Typlen : constant Uint := String_Type_Len (Etype (Right));
2034                Strlen : constant Uint :=
2035                  UI_From_Int (String_Length (Strval (Get_String_Val (Left))));
2036             begin
2037                Result := (Typlen = Strlen);
2038             end;
2039          end if;
2040
2041       --  Fold the membership test. We know we have a static range and Lo
2042       --  and Hi are set to the expressions for the end points of this range.
2043
2044       elsif Is_Real_Type (Etype (Right)) then
2045          declare
2046             Leftval : constant Ureal := Expr_Value_R (Left);
2047
2048          begin
2049             Result := Expr_Value_R (Lo) <= Leftval
2050                         and then Leftval <= Expr_Value_R (Hi);
2051          end;
2052
2053       else
2054          declare
2055             Leftval : constant Uint := Expr_Value (Left);
2056
2057          begin
2058             Result := Expr_Value (Lo) <= Leftval
2059                         and then Leftval <= Expr_Value (Hi);
2060          end;
2061       end if;
2062
2063       if Nkind (N) = N_Not_In then
2064          Result := not Result;
2065       end if;
2066
2067       Fold_Uint (N, Test (Result), True);
2068       Warn_On_Known_Condition (N);
2069    end Eval_Membership_Op;
2070
2071    ------------------------
2072    -- Eval_Named_Integer --
2073    ------------------------
2074
2075    procedure Eval_Named_Integer (N : Node_Id) is
2076    begin
2077       Fold_Uint (N,
2078         Expr_Value (Expression (Declaration_Node (Entity (N)))), True);
2079    end Eval_Named_Integer;
2080
2081    ---------------------
2082    -- Eval_Named_Real --
2083    ---------------------
2084
2085    procedure Eval_Named_Real (N : Node_Id) is
2086    begin
2087       Fold_Ureal (N,
2088         Expr_Value_R (Expression (Declaration_Node (Entity (N)))), True);
2089    end Eval_Named_Real;
2090
2091    -------------------
2092    -- Eval_Op_Expon --
2093    -------------------
2094
2095    --  Exponentiation is a static functions, so the result is potentially
2096    --  static if both operands are potentially static (RM 4.9(7), 4.9(20)).
2097
2098    procedure Eval_Op_Expon (N : Node_Id) is
2099       Left  : constant Node_Id := Left_Opnd (N);
2100       Right : constant Node_Id := Right_Opnd (N);
2101       Stat  : Boolean;
2102       Fold  : Boolean;
2103
2104    begin
2105       --  If not foldable we are done
2106
2107       Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold);
2108
2109       if not Fold then
2110          return;
2111       end if;
2112
2113       --  Fold exponentiation operation
2114
2115       declare
2116          Right_Int : constant Uint := Expr_Value (Right);
2117
2118       begin
2119          --  Integer case
2120
2121          if Is_Integer_Type (Etype (Left)) then
2122             declare
2123                Left_Int : constant Uint := Expr_Value (Left);
2124                Result   : Uint;
2125
2126             begin
2127                --  Exponentiation of an integer raises the exception
2128                --  Constraint_Error for a negative exponent (RM 4.5.6)
2129
2130                if Right_Int < 0 then
2131                   Apply_Compile_Time_Constraint_Error
2132                     (N, "integer exponent negative",
2133                      CE_Range_Check_Failed,
2134                      Warn => not Stat);
2135                   return;
2136
2137                else
2138                   if OK_Bits (N, Num_Bits (Left_Int) * Right_Int) then
2139                      Result := Left_Int ** Right_Int;
2140                   else
2141                      Result := Left_Int;
2142                   end if;
2143
2144                   if Is_Modular_Integer_Type (Etype (N)) then
2145                      Result := Result mod Modulus (Etype (N));
2146                   end if;
2147
2148                   Fold_Uint (N, Result, Stat);
2149                end if;
2150             end;
2151
2152          --  Real case
2153
2154          else
2155             declare
2156                Left_Real : constant Ureal := Expr_Value_R (Left);
2157
2158             begin
2159                --  Cannot have a zero base with a negative exponent
2160
2161                if UR_Is_Zero (Left_Real) then
2162
2163                   if Right_Int < 0 then
2164                      Apply_Compile_Time_Constraint_Error
2165                        (N, "zero ** negative integer",
2166                         CE_Range_Check_Failed,
2167                         Warn => not Stat);
2168                      return;
2169                   else
2170                      Fold_Ureal (N, Ureal_0, Stat);
2171                   end if;
2172
2173                else
2174                   Fold_Ureal (N, Left_Real ** Right_Int, Stat);
2175                end if;
2176             end;
2177          end if;
2178       end;
2179    end Eval_Op_Expon;
2180
2181    -----------------
2182    -- Eval_Op_Not --
2183    -----------------
2184
2185    --  The not operation is a  static functions, so the result is potentially
2186    --  static if the operand is potentially static (RM 4.9(7), 4.9(20)).
2187
2188    procedure Eval_Op_Not (N : Node_Id) is
2189       Right : constant Node_Id := Right_Opnd (N);
2190       Stat  : Boolean;
2191       Fold  : Boolean;
2192
2193    begin
2194       --  If not foldable we are done
2195
2196       Test_Expression_Is_Foldable (N, Right, Stat, Fold);
2197
2198       if not Fold then
2199          return;
2200       end if;
2201
2202       --  Fold not operation
2203
2204       declare
2205          Rint : constant Uint      := Expr_Value (Right);
2206          Typ  : constant Entity_Id := Etype (N);
2207
2208       begin
2209          --  Negation is equivalent to subtracting from the modulus minus
2210          --  one. For a binary modulus this is equivalent to the ones-
2211          --  component of the original value. For non-binary modulus this
2212          --  is an arbitrary but consistent definition.
2213
2214          if Is_Modular_Integer_Type (Typ) then
2215             Fold_Uint (N, Modulus (Typ) - 1 - Rint, Stat);
2216
2217          else
2218             pragma Assert (Is_Boolean_Type (Typ));
2219             Fold_Uint (N, Test (not Is_True (Rint)), Stat);
2220          end if;
2221
2222          Set_Is_Static_Expression (N, Stat);
2223       end;
2224    end Eval_Op_Not;
2225
2226    -------------------------------
2227    -- Eval_Qualified_Expression --
2228    -------------------------------
2229
2230    --  A qualified expression is potentially static if its subtype mark denotes
2231    --  a static subtype and its expression is potentially static (RM 4.9 (11)).
2232
2233    procedure Eval_Qualified_Expression (N : Node_Id) is
2234       Operand     : constant Node_Id   := Expression (N);
2235       Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
2236
2237       Stat : Boolean;
2238       Fold : Boolean;
2239       Hex  : Boolean;
2240
2241    begin
2242       --  Can only fold if target is string or scalar and subtype is static
2243       --  Also, do not fold if our parent is an allocator (this is because
2244       --  the qualified expression is really part of the syntactic structure
2245       --  of an allocator, and we do not want to end up with something that
2246       --  corresponds to "new 1" where the 1 is the result of folding a
2247       --  qualified expression).
2248
2249       if not Is_Static_Subtype (Target_Type)
2250         or else Nkind (Parent (N)) = N_Allocator
2251       then
2252          Check_Non_Static_Context (Operand);
2253
2254          --  If operand is known to raise constraint_error, set the
2255          --  flag on the expression so it does not get optimized away.
2256
2257          if Nkind (Operand) = N_Raise_Constraint_Error then
2258             Set_Raises_Constraint_Error (N);
2259          end if;
2260
2261          return;
2262       end if;
2263
2264       --  If not foldable we are done
2265
2266       Test_Expression_Is_Foldable (N, Operand, Stat, Fold);
2267
2268       if not Fold then
2269          return;
2270
2271       --  Don't try fold if target type has constraint error bounds
2272
2273       elsif not Is_OK_Static_Subtype (Target_Type) then
2274          Set_Raises_Constraint_Error (N);
2275          return;
2276       end if;
2277
2278       --  Here we will fold, save Print_In_Hex indication
2279
2280       Hex := Nkind (Operand) = N_Integer_Literal
2281                and then Print_In_Hex (Operand);
2282
2283       --  Fold the result of qualification
2284
2285       if Is_Discrete_Type (Target_Type) then
2286          Fold_Uint (N, Expr_Value (Operand), Stat);
2287
2288          --  Preserve Print_In_Hex indication
2289
2290          if Hex and then Nkind (N) = N_Integer_Literal then
2291             Set_Print_In_Hex (N);
2292          end if;
2293
2294       elsif Is_Real_Type (Target_Type) then
2295          Fold_Ureal (N, Expr_Value_R (Operand), Stat);
2296
2297       else
2298          Fold_Str (N, Strval (Get_String_Val (Operand)), Stat);
2299
2300          if not Stat then
2301             Set_Is_Static_Expression (N, False);
2302          else
2303             Check_String_Literal_Length (N, Target_Type);
2304          end if;
2305
2306          return;
2307       end if;
2308
2309       --  The expression may be foldable but not static
2310
2311       Set_Is_Static_Expression (N, Stat);
2312
2313       if Is_Out_Of_Range (N, Etype (N), Assume_Valid => True) then
2314          Out_Of_Range (N);
2315       end if;
2316    end Eval_Qualified_Expression;
2317
2318    -----------------------
2319    -- Eval_Real_Literal --
2320    -----------------------
2321
2322    --  Numeric literals are static (RM 4.9(1)), and have already been marked
2323    --  as static by the analyzer. The reason we did it that early is to allow
2324    --  the possibility of turning off the Is_Static_Expression flag after
2325    --  analysis, but before resolution, when integer literals are generated
2326    --  in the expander that do not correspond to static expressions.
2327
2328    procedure Eval_Real_Literal (N : Node_Id) is
2329       PK : constant Node_Kind := Nkind (Parent (N));
2330
2331    begin
2332       --  If the literal appears in a non-expression context
2333       --  and not as part of a number declaration, then it is
2334       --  appearing in a non-static context, so check it.
2335
2336       if PK not in N_Subexpr and then PK /= N_Number_Declaration then
2337          Check_Non_Static_Context (N);
2338       end if;
2339    end Eval_Real_Literal;
2340
2341    ------------------------
2342    -- Eval_Relational_Op --
2343    ------------------------
2344
2345    --  Relational operations are static functions, so the result is static
2346    --  if both operands are static (RM 4.9(7), 4.9(20)).
2347
2348    procedure Eval_Relational_Op (N : Node_Id) is
2349       Left   : constant Node_Id   := Left_Opnd (N);
2350       Right  : constant Node_Id   := Right_Opnd (N);
2351       Typ    : constant Entity_Id := Etype (Left);
2352       Result : Boolean;
2353       Stat   : Boolean;
2354       Fold   : Boolean;
2355
2356    begin
2357       --  One special case to deal with first. If we can tell that the result
2358       --  will be false because the lengths of one or more index subtypes are
2359       --  compile time known and different, then we can replace the entire
2360       --  result by False. We only do this for one dimensional arrays, because
2361       --  the case of multi-dimensional arrays is rare and too much trouble! If
2362       --  one of the operands is an illegal aggregate, its type might still be
2363       --  an arbitrary composite type, so nothing to do.
2364
2365       if Is_Array_Type (Typ)
2366         and then Typ /= Any_Composite
2367         and then Number_Dimensions (Typ) = 1
2368         and then (Nkind (N) = N_Op_Eq or else Nkind (N) = N_Op_Ne)
2369       then
2370          if Raises_Constraint_Error (Left)
2371            or else Raises_Constraint_Error (Right)
2372          then
2373             return;
2374          end if;
2375
2376          --  OK, we have the case where we may be able to do this fold
2377
2378          Length_Mismatch : declare
2379             procedure Get_Static_Length (Op : Node_Id; Len : out Uint);
2380             --  If Op is an expression for a constrained array with a known
2381             --  at compile time length, then Len is set to this (non-negative
2382             --  length). Otherwise Len is set to minus 1.
2383
2384             -----------------------
2385             -- Get_Static_Length --
2386             -----------------------
2387
2388             procedure Get_Static_Length (Op : Node_Id; Len : out Uint) is
2389                T : Entity_Id;
2390
2391             begin
2392                --  First easy case string literal
2393
2394                if Nkind (Op) = N_String_Literal then
2395                   Len := UI_From_Int (String_Length (Strval (Op)));
2396                   return;
2397                end if;
2398
2399                --  Second easy case, not constrained subtype, so no length
2400
2401                if not Is_Constrained (Etype (Op)) then
2402                   Len := Uint_Minus_1;
2403                   return;
2404                end if;
2405
2406                --  General case
2407
2408                T := Etype (First_Index (Etype (Op)));
2409
2410                --  The simple case, both bounds are known at compile time
2411
2412                if Is_Discrete_Type (T)
2413                  and then
2414                    Compile_Time_Known_Value (Type_Low_Bound (T))
2415                  and then
2416                    Compile_Time_Known_Value (Type_High_Bound (T))
2417                then
2418                   Len := UI_Max (Uint_0,
2419                                  Expr_Value (Type_High_Bound (T)) -
2420                                    Expr_Value (Type_Low_Bound  (T)) + 1);
2421                   return;
2422                end if;
2423
2424                --  A more complex case, where the bounds are of the form
2425                --  X [+/- K1] .. X [+/- K2]), where X is an expression that is
2426                --  either A'First or A'Last (with A an entity name), or X is an
2427                --  entity name, and the two X's are the same and K1 and K2 are
2428                --  known at compile time, in this case, the length can also be
2429                --  computed at compile time, even though the bounds are not
2430                --  known. A common case of this is e.g. (X'First..X'First+5).
2431
2432                Extract_Length : declare
2433                   procedure Decompose_Expr
2434                     (Expr : Node_Id;
2435                      Ent  : out Entity_Id;
2436                      Kind : out Character;
2437                      Cons : out Uint);
2438                   --  Given an expression, see if is of the form above,
2439                   --  X [+/- K]. If so Ent is set to the entity in X,
2440                   --  Kind is 'F','L','E' for 'First/'Last/simple entity,
2441                   --  and Cons is the value of K. If the expression is
2442                   --  not of the required form, Ent is set to Empty.
2443
2444                   --------------------
2445                   -- Decompose_Expr --
2446                   --------------------
2447
2448                   procedure Decompose_Expr
2449                     (Expr : Node_Id;
2450                      Ent  : out Entity_Id;
2451                      Kind : out Character;
2452                      Cons : out Uint)
2453                   is
2454                      Exp : Node_Id;
2455
2456                   begin
2457                      if Nkind (Expr) = N_Op_Add
2458                        and then Compile_Time_Known_Value (Right_Opnd (Expr))
2459                      then
2460                         Exp := Left_Opnd (Expr);
2461                         Cons := Expr_Value (Right_Opnd (Expr));
2462
2463                      elsif Nkind (Expr) = N_Op_Subtract
2464                        and then Compile_Time_Known_Value (Right_Opnd (Expr))
2465                      then
2466                         Exp := Left_Opnd (Expr);
2467                         Cons := -Expr_Value (Right_Opnd (Expr));
2468
2469                      else
2470                         Exp := Expr;
2471                         Cons := Uint_0;
2472                      end if;
2473
2474                      --  At this stage Exp is set to the potential X
2475
2476                      if Nkind (Exp) = N_Attribute_Reference then
2477                         if Attribute_Name (Exp) = Name_First then
2478                            Kind := 'F';
2479                         elsif Attribute_Name (Exp) = Name_Last then
2480                            Kind := 'L';
2481                         else
2482                            Ent := Empty;
2483                            return;
2484                         end if;
2485
2486                         Exp := Prefix (Exp);
2487
2488                      else
2489                         Kind := 'E';
2490                      end if;
2491
2492                      if Is_Entity_Name (Exp)
2493                        and then Present (Entity (Exp))
2494                      then
2495                         Ent := Entity (Exp);
2496                      else
2497                         Ent := Empty;
2498                      end if;
2499                   end Decompose_Expr;
2500
2501                   --  Local Variables
2502
2503                   Ent1,  Ent2  : Entity_Id;
2504                   Kind1, Kind2 : Character;
2505                   Cons1, Cons2 : Uint;
2506
2507                --  Start of processing for Extract_Length
2508
2509                begin
2510                   Decompose_Expr (Type_Low_Bound  (T), Ent1, Kind1, Cons1);
2511                   Decompose_Expr (Type_High_Bound (T), Ent2, Kind2, Cons2);
2512
2513                   if Present (Ent1)
2514                     and then Kind1 = Kind2
2515                     and then Ent1 = Ent2
2516                   then
2517                      Len := Cons2 - Cons1 + 1;
2518                   else
2519                      Len := Uint_Minus_1;
2520                   end if;
2521                end Extract_Length;
2522             end Get_Static_Length;
2523
2524             --  Local Variables
2525
2526             Len_L : Uint;
2527             Len_R : Uint;
2528
2529          --  Start of processing for Length_Mismatch
2530
2531          begin
2532             Get_Static_Length (Left,  Len_L);
2533             Get_Static_Length (Right, Len_R);
2534
2535             if Len_L /= Uint_Minus_1
2536               and then Len_R /= Uint_Minus_1
2537               and then Len_L /= Len_R
2538             then
2539                Fold_Uint (N, Test (Nkind (N) = N_Op_Ne), False);
2540                Warn_On_Known_Condition (N);
2541                return;
2542             end if;
2543          end Length_Mismatch;
2544       end if;
2545
2546       --  Another special case: comparisons of access types, where one or both
2547       --  operands are known to be null, so the result can be determined.
2548
2549       if Is_Access_Type (Typ) then
2550          if Known_Null (Left) then
2551             if Known_Null (Right) then
2552                Fold_Uint (N, Test (Nkind (N) = N_Op_Eq), False);
2553                Warn_On_Known_Condition (N);
2554                return;
2555
2556             elsif Known_Non_Null (Right) then
2557                Fold_Uint (N, Test (Nkind (N) = N_Op_Ne), False);
2558                Warn_On_Known_Condition (N);
2559                return;
2560             end if;
2561
2562          elsif Known_Non_Null (Left) then
2563             if Known_Null (Right) then
2564                Fold_Uint (N, Test (Nkind (N) = N_Op_Ne), False);
2565                Warn_On_Known_Condition (N);
2566                return;
2567             end if;
2568          end if;
2569       end if;
2570
2571       --  Can only fold if type is scalar (don't fold string ops)
2572
2573       if not Is_Scalar_Type (Typ) then
2574          Check_Non_Static_Context (Left);
2575          Check_Non_Static_Context (Right);
2576          return;
2577       end if;
2578
2579       --  If not foldable we are done
2580
2581       Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold);
2582
2583       if not Fold then
2584          return;
2585       end if;
2586
2587       --  Integer and Enumeration (discrete) type cases
2588
2589       if Is_Discrete_Type (Typ) then
2590          declare
2591             Left_Int  : constant Uint := Expr_Value (Left);
2592             Right_Int : constant Uint := Expr_Value (Right);
2593
2594          begin
2595             case Nkind (N) is
2596                when N_Op_Eq => Result := Left_Int =  Right_Int;
2597                when N_Op_Ne => Result := Left_Int /= Right_Int;
2598                when N_Op_Lt => Result := Left_Int <  Right_Int;
2599                when N_Op_Le => Result := Left_Int <= Right_Int;
2600                when N_Op_Gt => Result := Left_Int >  Right_Int;
2601                when N_Op_Ge => Result := Left_Int >= Right_Int;
2602
2603                when others =>
2604                   raise Program_Error;
2605             end case;
2606
2607             Fold_Uint (N, Test (Result), Stat);
2608          end;
2609
2610       --  Real type case
2611
2612       else
2613          pragma Assert (Is_Real_Type (Typ));
2614
2615          declare
2616             Left_Real  : constant Ureal := Expr_Value_R (Left);
2617             Right_Real : constant Ureal := Expr_Value_R (Right);
2618
2619          begin
2620             case Nkind (N) is
2621                when N_Op_Eq => Result := (Left_Real =  Right_Real);
2622                when N_Op_Ne => Result := (Left_Real /= Right_Real);
2623                when N_Op_Lt => Result := (Left_Real <  Right_Real);
2624                when N_Op_Le => Result := (Left_Real <= Right_Real);
2625                when N_Op_Gt => Result := (Left_Real >  Right_Real);
2626                when N_Op_Ge => Result := (Left_Real >= Right_Real);
2627
2628                when others =>
2629                   raise Program_Error;
2630             end case;
2631
2632             Fold_Uint (N, Test (Result), Stat);
2633          end;
2634       end if;
2635
2636       Warn_On_Known_Condition (N);
2637    end Eval_Relational_Op;
2638
2639    ----------------
2640    -- Eval_Shift --
2641    ----------------
2642
2643    --  Shift operations are intrinsic operations that can never be static,
2644    --  so the only processing required is to perform the required check for
2645    --  a non static context for the two operands.
2646
2647    --  Actually we could do some compile time evaluation here some time ???
2648
2649    procedure Eval_Shift (N : Node_Id) is
2650    begin
2651       Check_Non_Static_Context (Left_Opnd (N));
2652       Check_Non_Static_Context (Right_Opnd (N));
2653    end Eval_Shift;
2654
2655    ------------------------
2656    -- Eval_Short_Circuit --
2657    ------------------------
2658
2659    --  A short circuit operation is potentially static if both operands
2660    --  are potentially static (RM 4.9 (13))
2661
2662    procedure Eval_Short_Circuit (N : Node_Id) is
2663       Kind     : constant Node_Kind := Nkind (N);
2664       Left     : constant Node_Id   := Left_Opnd (N);
2665       Right    : constant Node_Id   := Right_Opnd (N);
2666       Left_Int : Uint;
2667       Rstat    : constant Boolean   :=
2668                    Is_Static_Expression (Left)
2669                      and then Is_Static_Expression (Right);
2670
2671    begin
2672       --  Short circuit operations are never static in Ada 83
2673
2674       if Ada_Version = Ada_83
2675         and then Comes_From_Source (N)
2676       then
2677          Check_Non_Static_Context (Left);
2678          Check_Non_Static_Context (Right);
2679          return;
2680       end if;
2681
2682       --  Now look at the operands, we can't quite use the normal call to
2683       --  Test_Expression_Is_Foldable here because short circuit operations
2684       --  are a special case, they can still be foldable, even if the right
2685       --  operand raises constraint error.
2686
2687       --  If either operand is Any_Type, just propagate to result and
2688       --  do not try to fold, this prevents cascaded errors.
2689
2690       if Etype (Left) = Any_Type or else Etype (Right) = Any_Type then
2691          Set_Etype (N, Any_Type);
2692          return;
2693
2694       --  If left operand raises constraint error, then replace node N with
2695       --  the raise constraint error node, and we are obviously not foldable.
2696       --  Is_Static_Expression is set from the two operands in the normal way,
2697       --  and we check the right operand if it is in a non-static context.
2698
2699       elsif Raises_Constraint_Error (Left) then
2700          if not Rstat then
2701             Check_Non_Static_Context (Right);
2702          end if;
2703
2704          Rewrite_In_Raise_CE (N, Left);
2705          Set_Is_Static_Expression (N, Rstat);
2706          return;
2707
2708       --  If the result is not static, then we won't in any case fold
2709
2710       elsif not Rstat then
2711          Check_Non_Static_Context (Left);
2712          Check_Non_Static_Context (Right);
2713          return;
2714       end if;
2715
2716       --  Here the result is static, note that, unlike the normal processing
2717       --  in Test_Expression_Is_Foldable, we did *not* check above to see if
2718       --  the right operand raises constraint error, that's because it is not
2719       --  significant if the left operand is decisive.
2720
2721       Set_Is_Static_Expression (N);
2722
2723       --  It does not matter if the right operand raises constraint error if
2724       --  it will not be evaluated. So deal specially with the cases where
2725       --  the right operand is not evaluated. Note that we will fold these
2726       --  cases even if the right operand is non-static, which is fine, but
2727       --  of course in these cases the result is not potentially static.
2728
2729       Left_Int := Expr_Value (Left);
2730
2731       if (Kind = N_And_Then and then Is_False (Left_Int))
2732         or else (Kind = N_Or_Else and Is_True (Left_Int))
2733       then
2734          Fold_Uint (N, Left_Int, Rstat);
2735          return;
2736       end if;
2737
2738       --  If first operand not decisive, then it does matter if the right
2739       --  operand raises constraint error, since it will be evaluated, so
2740       --  we simply replace the node with the right operand. Note that this
2741       --  properly propagates Is_Static_Expression and Raises_Constraint_Error
2742       --  (both are set to True in Right).
2743
2744       if Raises_Constraint_Error (Right) then
2745          Rewrite_In_Raise_CE (N, Right);
2746          Check_Non_Static_Context (Left);
2747          return;
2748       end if;
2749
2750       --  Otherwise the result depends on the right operand
2751
2752       Fold_Uint (N, Expr_Value (Right), Rstat);
2753       return;
2754    end Eval_Short_Circuit;
2755
2756    ----------------
2757    -- Eval_Slice --
2758    ----------------
2759
2760    --  Slices can never be static, so the only processing required is to
2761    --  check for non-static context if an explicit range is given.
2762
2763    procedure Eval_Slice (N : Node_Id) is
2764       Drange : constant Node_Id := Discrete_Range (N);
2765    begin
2766       if Nkind (Drange) = N_Range then
2767          Check_Non_Static_Context (Low_Bound (Drange));
2768          Check_Non_Static_Context (High_Bound (Drange));
2769       end if;
2770
2771       --  A slice of the form  A (subtype), when the subtype is the index of
2772       --  the type of A, is redundant, the slice can be replaced with A, and
2773       --  this is worth a warning.
2774
2775       if Is_Entity_Name (Prefix (N)) then
2776          declare
2777             E : constant Entity_Id := Entity (Prefix (N));
2778             T : constant Entity_Id := Etype (E);
2779          begin
2780             if Ekind (E) = E_Constant
2781               and then Is_Array_Type (T)
2782               and then Is_Entity_Name (Drange)
2783             then
2784                if Is_Entity_Name (Original_Node (First_Index (T)))
2785                  and then Entity (Original_Node (First_Index (T)))
2786                     = Entity (Drange)
2787                then
2788                   if Warn_On_Redundant_Constructs then
2789                      Error_Msg_N ("redundant slice denotes whole array?", N);
2790                   end if;
2791
2792                   --  The following might be a useful optimization ????
2793
2794                   --  Rewrite (N, New_Occurrence_Of (E, Sloc (N)));
2795                end if;
2796             end if;
2797          end;
2798       end if;
2799    end Eval_Slice;
2800
2801    -------------------------
2802    -- Eval_String_Literal --
2803    -------------------------
2804
2805    procedure Eval_String_Literal (N : Node_Id) is
2806       Typ : constant Entity_Id := Etype (N);
2807       Bas : constant Entity_Id := Base_Type (Typ);
2808       Xtp : Entity_Id;
2809       Len : Nat;
2810       Lo  : Node_Id;
2811
2812    begin
2813       --  Nothing to do if error type (handles cases like default expressions
2814       --  or generics where we have not yet fully resolved the type)
2815
2816       if Bas = Any_Type or else Bas = Any_String then
2817          return;
2818       end if;
2819
2820       --  String literals are static if the subtype is static (RM 4.9(2)), so
2821       --  reset the static expression flag (it was set unconditionally in
2822       --  Analyze_String_Literal) if the subtype is non-static. We tell if
2823       --  the subtype is static by looking at the lower bound.
2824
2825       if Ekind (Typ) = E_String_Literal_Subtype then
2826          if not Is_OK_Static_Expression (String_Literal_Low_Bound (Typ)) then
2827             Set_Is_Static_Expression (N, False);
2828             return;
2829          end if;
2830
2831       --  Here if Etype of string literal is normal Etype (not yet possible,
2832       --  but may be possible in future!)
2833
2834       elsif not Is_OK_Static_Expression
2835                     (Type_Low_Bound (Etype (First_Index (Typ))))
2836       then
2837          Set_Is_Static_Expression (N, False);
2838          return;
2839       end if;
2840
2841       --  If original node was a type conversion, then result if non-static
2842
2843       if Nkind (Original_Node (N)) = N_Type_Conversion then
2844          Set_Is_Static_Expression (N, False);
2845          return;
2846       end if;
2847
2848       --  Test for illegal Ada 95 cases. A string literal is illegal in
2849       --  Ada 95 if its bounds are outside the index base type and this
2850       --  index type is static. This can happen in only two ways. Either
2851       --  the string literal is too long, or it is null, and the lower
2852       --  bound is type'First. In either case it is the upper bound that
2853       --  is out of range of the index type.
2854
2855       if Ada_Version >= Ada_95 then
2856          if Root_Type (Bas) = Standard_String
2857               or else
2858             Root_Type (Bas) = Standard_Wide_String
2859          then
2860             Xtp := Standard_Positive;
2861          else
2862             Xtp := Etype (First_Index (Bas));
2863          end if;
2864
2865          if Ekind (Typ) = E_String_Literal_Subtype then
2866             Lo := String_Literal_Low_Bound (Typ);
2867          else
2868             Lo := Type_Low_Bound (Etype (First_Index (Typ)));
2869          end if;
2870
2871          Len := String_Length (Strval (N));
2872
2873          if UI_From_Int (Len) > String_Type_Len (Bas) then
2874             Apply_Compile_Time_Constraint_Error
2875               (N, "string literal too long for}", CE_Length_Check_Failed,
2876                Ent => Bas,
2877                Typ => First_Subtype (Bas));
2878
2879          elsif Len = 0
2880            and then not Is_Generic_Type (Xtp)
2881            and then
2882              Expr_Value (Lo) = Expr_Value (Type_Low_Bound (Base_Type (Xtp)))
2883          then
2884             Apply_Compile_Time_Constraint_Error
2885               (N, "null string literal not allowed for}",
2886                CE_Length_Check_Failed,
2887                Ent => Bas,
2888                Typ => First_Subtype (Bas));
2889          end if;
2890       end if;
2891    end Eval_String_Literal;
2892
2893    --------------------------
2894    -- Eval_Type_Conversion --
2895    --------------------------
2896
2897    --  A type conversion is potentially static if its subtype mark is for a
2898    --  static scalar subtype, and its operand expression is potentially static
2899    --  (RM 4.9 (10))
2900
2901    procedure Eval_Type_Conversion (N : Node_Id) is
2902       Operand     : constant Node_Id   := Expression (N);
2903       Source_Type : constant Entity_Id := Etype (Operand);
2904       Target_Type : constant Entity_Id := Etype (N);
2905
2906       Stat   : Boolean;
2907       Fold   : Boolean;
2908
2909       function To_Be_Treated_As_Integer (T : Entity_Id) return Boolean;
2910       --  Returns true if type T is an integer type, or if it is a
2911       --  fixed-point type to be treated as an integer (i.e. the flag
2912       --  Conversion_OK is set on the conversion node).
2913
2914       function To_Be_Treated_As_Real (T : Entity_Id) return Boolean;
2915       --  Returns true if type T is a floating-point type, or if it is a
2916       --  fixed-point type that is not to be treated as an integer (i.e. the
2917       --  flag Conversion_OK is not set on the conversion node).
2918
2919       ------------------------------
2920       -- To_Be_Treated_As_Integer --
2921       ------------------------------
2922
2923       function To_Be_Treated_As_Integer (T : Entity_Id) return Boolean is
2924       begin
2925          return
2926            Is_Integer_Type (T)
2927              or else (Is_Fixed_Point_Type (T) and then Conversion_OK (N));
2928       end To_Be_Treated_As_Integer;
2929
2930       ---------------------------
2931       -- To_Be_Treated_As_Real --
2932       ---------------------------
2933
2934       function To_Be_Treated_As_Real (T : Entity_Id) return Boolean is
2935       begin
2936          return
2937            Is_Floating_Point_Type (T)
2938              or else (Is_Fixed_Point_Type (T) and then not Conversion_OK (N));
2939       end To_Be_Treated_As_Real;
2940
2941    --  Start of processing for Eval_Type_Conversion
2942
2943    begin
2944       --  Cannot fold if target type is non-static or if semantic error
2945
2946       if not Is_Static_Subtype (Target_Type) then
2947          Check_Non_Static_Context (Operand);
2948          return;
2949
2950       elsif Error_Posted (N) then
2951          return;
2952       end if;
2953
2954       --  If not foldable we are done
2955
2956       Test_Expression_Is_Foldable (N, Operand, Stat, Fold);
2957
2958       if not Fold then
2959          return;
2960
2961       --  Don't try fold if target type has constraint error bounds
2962
2963       elsif not Is_OK_Static_Subtype (Target_Type) then
2964          Set_Raises_Constraint_Error (N);
2965          return;
2966       end if;
2967
2968       --  Remaining processing depends on operand types. Note that in the
2969       --  following type test, fixed-point counts as real unless the flag
2970       --  Conversion_OK is set, in which case it counts as integer.
2971
2972       --  Fold conversion, case of string type. The result is not static
2973
2974       if Is_String_Type (Target_Type) then
2975          Fold_Str (N, Strval (Get_String_Val (Operand)), Static => False);
2976
2977          return;
2978
2979       --  Fold conversion, case of integer target type
2980
2981       elsif To_Be_Treated_As_Integer (Target_Type) then
2982          declare
2983             Result : Uint;
2984
2985          begin
2986             --  Integer to integer conversion
2987
2988             if To_Be_Treated_As_Integer (Source_Type) then
2989                Result := Expr_Value (Operand);
2990
2991             --  Real to integer conversion
2992
2993             else
2994                Result := UR_To_Uint (Expr_Value_R (Operand));
2995             end if;
2996
2997             --  If fixed-point type (Conversion_OK must be set), then the
2998             --  result is logically an integer, but we must replace the
2999             --  conversion with the corresponding real literal, since the
3000             --  type from a semantic point of view is still fixed-point.
3001
3002             if Is_Fixed_Point_Type (Target_Type) then
3003                Fold_Ureal
3004                  (N, UR_From_Uint (Result) * Small_Value (Target_Type), Stat);
3005
3006             --  Otherwise result is integer literal
3007
3008             else
3009                Fold_Uint (N, Result, Stat);
3010             end if;
3011          end;
3012
3013       --  Fold conversion, case of real target type
3014
3015       elsif To_Be_Treated_As_Real (Target_Type) then
3016          declare
3017             Result : Ureal;
3018
3019          begin
3020             if To_Be_Treated_As_Real (Source_Type) then
3021                Result := Expr_Value_R (Operand);
3022             else
3023                Result := UR_From_Uint (Expr_Value (Operand));
3024             end if;
3025
3026             Fold_Ureal (N, Result, Stat);
3027          end;
3028
3029       --  Enumeration types
3030
3031       else
3032          Fold_Uint (N, Expr_Value (Operand), Stat);
3033       end if;
3034
3035       if Is_Out_Of_Range (N, Etype (N), Assume_Valid => True) then
3036          Out_Of_Range (N);
3037       end if;
3038
3039    end Eval_Type_Conversion;
3040
3041    -------------------
3042    -- Eval_Unary_Op --
3043    -------------------
3044
3045    --  Predefined unary operators are static functions (RM 4.9(20)) and thus
3046    --  are potentially static if the operand is potentially static (RM 4.9(7))
3047
3048    procedure Eval_Unary_Op (N : Node_Id) is
3049       Right : constant Node_Id := Right_Opnd (N);
3050       Stat  : Boolean;
3051       Fold  : Boolean;
3052
3053    begin
3054       --  If not foldable we are done
3055
3056       Test_Expression_Is_Foldable (N, Right, Stat, Fold);
3057
3058       if not Fold then
3059          return;
3060       end if;
3061
3062       --  Fold for integer case
3063
3064       if Is_Integer_Type (Etype (N)) then
3065          declare
3066             Rint   : constant Uint := Expr_Value (Right);
3067             Result : Uint;
3068
3069          begin
3070             --  In the case of modular unary plus and abs there is no need
3071             --  to adjust the result of the operation since if the original
3072             --  operand was in bounds the result will be in the bounds of the
3073             --  modular type. However, in the case of modular unary minus the
3074             --  result may go out of the bounds of the modular type and needs
3075             --  adjustment.
3076
3077             if Nkind (N) = N_Op_Plus then
3078                Result := Rint;
3079
3080             elsif Nkind (N) = N_Op_Minus then
3081                if Is_Modular_Integer_Type (Etype (N)) then
3082                   Result := (-Rint) mod Modulus (Etype (N));
3083                else
3084                   Result := (-Rint);
3085                end if;
3086
3087             else
3088                pragma Assert (Nkind (N) = N_Op_Abs);
3089                Result := abs Rint;
3090             end if;
3091
3092             Fold_Uint (N, Result, Stat);
3093          end;
3094
3095       --  Fold for real case
3096
3097       elsif Is_Real_Type (Etype (N)) then
3098          declare
3099             Rreal  : constant Ureal := Expr_Value_R (Right);
3100             Result : Ureal;
3101
3102          begin
3103             if Nkind (N) = N_Op_Plus then
3104                Result := Rreal;
3105
3106             elsif Nkind (N) = N_Op_Minus then
3107                Result := UR_Negate (Rreal);
3108
3109             else
3110                pragma Assert (Nkind (N) = N_Op_Abs);
3111                Result := abs Rreal;
3112             end if;
3113
3114             Fold_Ureal (N, Result, Stat);
3115          end;
3116       end if;
3117    end Eval_Unary_Op;
3118
3119    -------------------------------
3120    -- Eval_Unchecked_Conversion --
3121    -------------------------------
3122
3123    --  Unchecked conversions can never be static, so the only required
3124    --  processing is to check for a non-static context for the operand.
3125
3126    procedure Eval_Unchecked_Conversion (N : Node_Id) is
3127    begin
3128       Check_Non_Static_Context (Expression (N));
3129    end Eval_Unchecked_Conversion;
3130
3131    --------------------
3132    -- Expr_Rep_Value --
3133    --------------------
3134
3135    function Expr_Rep_Value (N : Node_Id) return Uint is
3136       Kind : constant Node_Kind := Nkind (N);
3137       Ent  : Entity_Id;
3138
3139    begin
3140       if Is_Entity_Name (N) then
3141          Ent := Entity (N);
3142
3143          --  An enumeration literal that was either in the source or
3144          --  created as a result of static evaluation.
3145
3146          if Ekind (Ent) = E_Enumeration_Literal then
3147             return Enumeration_Rep (Ent);
3148
3149          --  A user defined static constant
3150
3151          else
3152             pragma Assert (Ekind (Ent) = E_Constant);
3153             return Expr_Rep_Value (Constant_Value (Ent));
3154          end if;
3155
3156       --  An integer literal that was either in the source or created
3157       --  as a result of static evaluation.
3158
3159       elsif Kind = N_Integer_Literal then
3160          return Intval (N);
3161
3162       --  A real literal for a fixed-point type. This must be the fixed-point
3163       --  case, either the literal is of a fixed-point type, or it is a bound
3164       --  of a fixed-point type, with type universal real. In either case we
3165       --  obtain the desired value from Corresponding_Integer_Value.
3166
3167       elsif Kind = N_Real_Literal then
3168          pragma Assert (Is_Fixed_Point_Type (Underlying_Type (Etype (N))));
3169          return Corresponding_Integer_Value (N);
3170
3171       --  Peculiar VMS case, if we have xxx'Null_Parameter, return zero
3172
3173       elsif Kind = N_Attribute_Reference
3174         and then Attribute_Name (N) = Name_Null_Parameter
3175       then
3176          return Uint_0;
3177
3178       --  Otherwise must be character literal
3179
3180       else
3181          pragma Assert (Kind = N_Character_Literal);
3182          Ent := Entity (N);
3183
3184          --  Since Character literals of type Standard.Character don't
3185          --  have any defining character literals built for them, they
3186          --  do not have their Entity set, so just use their Char
3187          --  code. Otherwise for user-defined character literals use
3188          --  their Pos value as usual which is the same as the Rep value.
3189
3190          if No (Ent) then
3191             return Char_Literal_Value (N);
3192          else
3193             return Enumeration_Rep (Ent);
3194          end if;
3195       end if;
3196    end Expr_Rep_Value;
3197
3198    ----------------
3199    -- Expr_Value --
3200    ----------------
3201
3202    function Expr_Value (N : Node_Id) return Uint is
3203       Kind   : constant Node_Kind := Nkind (N);
3204       CV_Ent : CV_Entry renames CV_Cache (Nat (N) mod CV_Cache_Size);
3205       Ent    : Entity_Id;
3206       Val    : Uint;
3207
3208    begin
3209       --  If already in cache, then we know it's compile time known and we can
3210       --  return the value that was previously stored in the cache since
3211       --  compile time known values cannot change.
3212
3213       if CV_Ent.N = N then
3214          return CV_Ent.V;
3215       end if;
3216
3217       --  Otherwise proceed to test value
3218
3219       if Is_Entity_Name (N) then
3220          Ent := Entity (N);
3221
3222          --  An enumeration literal that was either in the source or
3223          --  created as a result of static evaluation.
3224
3225          if Ekind (Ent) = E_Enumeration_Literal then
3226             Val := Enumeration_Pos (Ent);
3227
3228          --  A user defined static constant
3229
3230          else
3231             pragma Assert (Ekind (Ent) = E_Constant);
3232             Val := Expr_Value (Constant_Value (Ent));
3233          end if;
3234
3235       --  An integer literal that was either in the source or created
3236       --  as a result of static evaluation.
3237
3238       elsif Kind = N_Integer_Literal then
3239          Val := Intval (N);
3240
3241       --  A real literal for a fixed-point type. This must be the fixed-point
3242       --  case, either the literal is of a fixed-point type, or it is a bound
3243       --  of a fixed-point type, with type universal real. In either case we
3244       --  obtain the desired value from Corresponding_Integer_Value.
3245
3246       elsif Kind = N_Real_Literal then
3247
3248          pragma Assert (Is_Fixed_Point_Type (Underlying_Type (Etype (N))));
3249          Val := Corresponding_Integer_Value (N);
3250
3251       --  Peculiar VMS case, if we have xxx'Null_Parameter, return zero
3252
3253       elsif Kind = N_Attribute_Reference
3254         and then Attribute_Name (N) = Name_Null_Parameter
3255       then
3256          Val := Uint_0;
3257
3258       --  Otherwise must be character literal
3259
3260       else
3261          pragma Assert (Kind = N_Character_Literal);
3262          Ent := Entity (N);
3263
3264          --  Since Character literals of type Standard.Character don't
3265          --  have any defining character literals built for them, they
3266          --  do not have their Entity set, so just use their Char
3267          --  code. Otherwise for user-defined character literals use
3268          --  their Pos value as usual.
3269
3270          if No (Ent) then
3271             Val := Char_Literal_Value (N);
3272          else
3273             Val := Enumeration_Pos (Ent);
3274          end if;
3275       end if;
3276
3277       --  Come here with Val set to value to be returned, set cache
3278
3279       CV_Ent.N := N;
3280       CV_Ent.V := Val;
3281       return Val;
3282    end Expr_Value;
3283
3284    ------------------
3285    -- Expr_Value_E --
3286    ------------------
3287
3288    function Expr_Value_E (N : Node_Id) return Entity_Id is
3289       Ent  : constant Entity_Id := Entity (N);
3290
3291    begin
3292       if Ekind (Ent) = E_Enumeration_Literal then
3293          return Ent;
3294       else
3295          pragma Assert (Ekind (Ent) = E_Constant);
3296          return Expr_Value_E (Constant_Value (Ent));
3297       end if;
3298    end Expr_Value_E;
3299
3300    ------------------
3301    -- Expr_Value_R --
3302    ------------------
3303
3304    function Expr_Value_R (N : Node_Id) return Ureal is
3305       Kind : constant Node_Kind := Nkind (N);
3306       Ent  : Entity_Id;
3307       Expr : Node_Id;
3308
3309    begin
3310       if Kind = N_Real_Literal then
3311          return Realval (N);
3312
3313       elsif Kind = N_Identifier or else Kind = N_Expanded_Name then
3314          Ent := Entity (N);
3315          pragma Assert (Ekind (Ent) = E_Constant);
3316          return Expr_Value_R (Constant_Value (Ent));
3317
3318       elsif Kind = N_Integer_Literal then
3319          return UR_From_Uint (Expr_Value (N));
3320
3321       --  Strange case of VAX literals, which are at this stage transformed
3322       --  into Vax_Type!x_To_y(IEEE_Literal). See Expand_N_Real_Literal in
3323       --  Exp_Vfpt for further details.
3324
3325       elsif Vax_Float (Etype (N))
3326         and then Nkind (N) = N_Unchecked_Type_Conversion
3327       then
3328          Expr := Expression (N);
3329
3330          if Nkind (Expr) = N_Function_Call
3331            and then Present (Parameter_Associations (Expr))
3332          then
3333             Expr := First (Parameter_Associations (Expr));
3334
3335             if Nkind (Expr) = N_Real_Literal then
3336                return Realval (Expr);
3337             end if;
3338          end if;
3339
3340       --  Peculiar VMS case, if we have xxx'Null_Parameter, return 0.0
3341
3342       elsif Kind = N_Attribute_Reference
3343         and then Attribute_Name (N) = Name_Null_Parameter
3344       then
3345          return Ureal_0;
3346       end if;
3347
3348       --  If we fall through, we have a node that cannot be interpreted
3349       --  as a compile time constant. That is definitely an error.
3350
3351       raise Program_Error;
3352    end Expr_Value_R;
3353
3354    ------------------
3355    -- Expr_Value_S --
3356    ------------------
3357
3358    function Expr_Value_S (N : Node_Id) return Node_Id is
3359    begin
3360       if Nkind (N) = N_String_Literal then
3361          return N;
3362       else
3363          pragma Assert (Ekind (Entity (N)) = E_Constant);
3364          return Expr_Value_S (Constant_Value (Entity (N)));
3365       end if;
3366    end Expr_Value_S;
3367
3368    --------------------------
3369    -- Flag_Non_Static_Expr --
3370    --------------------------
3371
3372    procedure Flag_Non_Static_Expr (Msg : String; Expr : Node_Id) is
3373    begin
3374       if Error_Posted (Expr) and then not All_Errors_Mode then
3375          return;
3376       else
3377          Error_Msg_F (Msg, Expr);
3378          Why_Not_Static (Expr);
3379       end if;
3380    end Flag_Non_Static_Expr;
3381
3382    --------------
3383    -- Fold_Str --
3384    --------------
3385
3386    procedure Fold_Str (N : Node_Id; Val : String_Id; Static : Boolean) is
3387       Loc : constant Source_Ptr := Sloc (N);
3388       Typ : constant Entity_Id  := Etype (N);
3389
3390    begin
3391       Rewrite (N, Make_String_Literal (Loc, Strval => Val));
3392
3393       --  We now have the literal with the right value, both the actual type
3394       --  and the expected type of this literal are taken from the expression
3395       --  that was evaluated.
3396
3397       Analyze (N);
3398       Set_Is_Static_Expression (N, Static);
3399       Set_Etype (N, Typ);
3400       Resolve (N);
3401    end Fold_Str;
3402
3403    ---------------
3404    -- Fold_Uint --
3405    ---------------
3406
3407    procedure Fold_Uint (N : Node_Id; Val : Uint; Static : Boolean) is
3408       Loc : constant Source_Ptr := Sloc (N);
3409       Typ : Entity_Id  := Etype (N);
3410       Ent : Entity_Id;
3411
3412    begin
3413       --  If we are folding a named number, retain the entity in the
3414       --  literal, for ASIS use.
3415
3416       if Is_Entity_Name (N)
3417         and then Ekind (Entity (N)) = E_Named_Integer
3418       then
3419          Ent := Entity (N);
3420       else
3421          Ent := Empty;
3422       end if;
3423
3424       if Is_Private_Type (Typ) then
3425          Typ := Full_View (Typ);
3426       end if;
3427
3428       --  For a result of type integer, substitute an N_Integer_Literal node
3429       --  for the result of the compile time evaluation of the expression.
3430       --  For ASIS use, set a link to the original named number when not in
3431       --  a generic context.
3432
3433       if Is_Integer_Type (Typ) then
3434          Rewrite (N, Make_Integer_Literal (Loc, Val));
3435
3436          Set_Original_Entity (N, Ent);
3437
3438       --  Otherwise we have an enumeration type, and we substitute either
3439       --  an N_Identifier or N_Character_Literal to represent the enumeration
3440       --  literal corresponding to the given value, which must always be in
3441       --  range, because appropriate tests have already been made for this.
3442
3443       else pragma Assert (Is_Enumeration_Type (Typ));
3444          Rewrite (N, Get_Enum_Lit_From_Pos (Etype (N), Val, Loc));
3445       end if;
3446
3447       --  We now have the literal with the right value, both the actual type
3448       --  and the expected type of this literal are taken from the expression
3449       --  that was evaluated.
3450
3451       Analyze (N);
3452       Set_Is_Static_Expression (N, Static);
3453       Set_Etype (N, Typ);
3454       Resolve (N);
3455    end Fold_Uint;
3456
3457    ----------------
3458    -- Fold_Ureal --
3459    ----------------
3460
3461    procedure Fold_Ureal (N : Node_Id; Val : Ureal; Static : Boolean) is
3462       Loc : constant Source_Ptr := Sloc (N);
3463       Typ : constant Entity_Id  := Etype (N);
3464       Ent : Entity_Id;
3465
3466    begin
3467       --  If we are folding a named number, retain the entity in the
3468       --  literal, for ASIS use.
3469
3470       if Is_Entity_Name (N)
3471         and then Ekind (Entity (N)) = E_Named_Real
3472       then
3473          Ent := Entity (N);
3474       else
3475          Ent := Empty;
3476       end if;
3477
3478       Rewrite (N, Make_Real_Literal (Loc, Realval => Val));
3479
3480       --  Set link to original named number, for ASIS use
3481
3482       Set_Original_Entity (N, Ent);
3483
3484       --  Both the actual and expected type comes from the original expression
3485
3486       Analyze (N);
3487       Set_Is_Static_Expression (N, Static);
3488       Set_Etype (N, Typ);
3489       Resolve (N);
3490    end Fold_Ureal;
3491
3492    ---------------
3493    -- From_Bits --
3494    ---------------
3495
3496    function From_Bits (B : Bits; T : Entity_Id) return Uint is
3497       V : Uint := Uint_0;
3498
3499    begin
3500       for J in 0 .. B'Last loop
3501          if B (J) then
3502             V := V + 2 ** J;
3503          end if;
3504       end loop;
3505
3506       if Non_Binary_Modulus (T) then
3507          V := V mod Modulus (T);
3508       end if;
3509
3510       return V;
3511    end From_Bits;
3512
3513    --------------------
3514    -- Get_String_Val --
3515    --------------------
3516
3517    function Get_String_Val (N : Node_Id) return Node_Id is
3518    begin
3519       if Nkind (N) = N_String_Literal then
3520          return N;
3521
3522       elsif Nkind (N) = N_Character_Literal then
3523          return N;
3524
3525       else
3526          pragma Assert (Is_Entity_Name (N));
3527          return Get_String_Val (Constant_Value (Entity (N)));
3528       end if;
3529    end Get_String_Val;
3530
3531    ----------------
3532    -- Initialize --
3533    ----------------
3534
3535    procedure Initialize is
3536    begin
3537       CV_Cache := (others => (Node_High_Bound, Uint_0));
3538    end Initialize;
3539
3540    --------------------
3541    -- In_Subrange_Of --
3542    --------------------
3543
3544    function In_Subrange_Of
3545      (T1        : Entity_Id;
3546       T2        : Entity_Id;
3547       Fixed_Int : Boolean := False) return Boolean
3548    is
3549       L1 : Node_Id;
3550       H1 : Node_Id;
3551
3552       L2 : Node_Id;
3553       H2 : Node_Id;
3554
3555    begin
3556       if T1 = T2 or else Is_Subtype_Of (T1, T2) then
3557          return True;
3558
3559       --  Never in range if both types are not scalar. Don't know if this can
3560       --  actually happen, but just in case.
3561
3562       elsif not Is_Scalar_Type (T1) or else not Is_Scalar_Type (T1) then
3563          return False;
3564
3565       else
3566          L1 := Type_Low_Bound  (T1);
3567          H1 := Type_High_Bound (T1);
3568
3569          L2 := Type_Low_Bound  (T2);
3570          H2 := Type_High_Bound (T2);
3571
3572          --  Check bounds to see if comparison possible at compile time
3573
3574          if Compile_Time_Compare (L1, L2, Assume_Valid => True) in Compare_GE
3575               and then
3576             Compile_Time_Compare (H1, H2, Assume_Valid => True) in Compare_LE
3577          then
3578             return True;
3579          end if;
3580
3581          --  If bounds not comparable at compile time, then the bounds of T2
3582          --  must be compile time known or we cannot answer the query.
3583
3584          if not Compile_Time_Known_Value (L2)
3585            or else not Compile_Time_Known_Value (H2)
3586          then
3587             return False;
3588          end if;
3589
3590          --  If the bounds of T1 are know at compile time then use these
3591          --  ones, otherwise use the bounds of the base type (which are of
3592          --  course always static).
3593
3594          if not Compile_Time_Known_Value (L1) then
3595             L1 := Type_Low_Bound (Base_Type (T1));
3596          end if;
3597
3598          if not Compile_Time_Known_Value (H1) then
3599             H1 := Type_High_Bound (Base_Type (T1));
3600          end if;
3601
3602          --  Fixed point types should be considered as such only if
3603          --  flag Fixed_Int is set to False.
3604
3605          if Is_Floating_Point_Type (T1) or else Is_Floating_Point_Type (T2)
3606            or else (Is_Fixed_Point_Type (T1) and then not Fixed_Int)
3607            or else (Is_Fixed_Point_Type (T2) and then not Fixed_Int)
3608          then
3609             return
3610               Expr_Value_R (L2) <= Expr_Value_R (L1)
3611                 and then
3612               Expr_Value_R (H2) >= Expr_Value_R (H1);
3613
3614          else
3615             return
3616               Expr_Value (L2) <= Expr_Value (L1)
3617                 and then
3618               Expr_Value (H2) >= Expr_Value (H1);
3619
3620          end if;
3621       end if;
3622
3623    --  If any exception occurs, it means that we have some bug in the compiler
3624    --  possibly triggered by a previous error, or by some unforeseen peculiar
3625    --  occurrence. However, this is only an optimization attempt, so there is
3626    --  really no point in crashing the compiler. Instead we just decide, too
3627    --  bad, we can't figure out the answer in this case after all.
3628
3629    exception
3630       when others =>
3631
3632          --  Debug flag K disables this behavior (useful for debugging)
3633
3634          if Debug_Flag_K then
3635             raise;
3636          else
3637             return False;
3638          end if;
3639    end In_Subrange_Of;
3640
3641    -----------------
3642    -- Is_In_Range --
3643    -----------------
3644
3645    function Is_In_Range
3646      (N            : Node_Id;
3647       Typ          : Entity_Id;
3648       Assume_Valid : Boolean := False;
3649       Fixed_Int    : Boolean := False;
3650       Int_Real     : Boolean := False) return Boolean
3651    is
3652       Val  : Uint;
3653       Valr : Ureal;
3654
3655       pragma Warnings (Off, Assume_Valid);
3656       --  For now Assume_Valid is unreferenced since the current implementation
3657       --  always returns False if N is not a compile time known value, but we
3658       --  keep the parameter to allow for future enhancements in which we try
3659       --  to get the information in the variable case as well.
3660
3661    begin
3662       --  Universal types have no range limits, so always in range
3663
3664       if Typ = Universal_Integer or else Typ = Universal_Real then
3665          return True;
3666
3667       --  Never in range if not scalar type. Don't know if this can
3668       --  actually happen, but our spec allows it, so we must check!
3669
3670       elsif not Is_Scalar_Type (Typ) then
3671          return False;
3672
3673       --  Never in range unless we have a compile time known value
3674
3675       elsif not Compile_Time_Known_Value (N) then
3676          return False;
3677
3678       --  General processing with a known compile time value
3679
3680       else
3681          declare
3682             Lo       : Node_Id;
3683             Hi       : Node_Id;
3684             LB_Known : Boolean;
3685             UB_Known : Boolean;
3686
3687          begin
3688             Lo := Type_Low_Bound  (Typ);
3689             Hi := Type_High_Bound (Typ);
3690
3691             LB_Known := Compile_Time_Known_Value (Lo);
3692             UB_Known := Compile_Time_Known_Value (Hi);
3693
3694             --  Fixed point types should be considered as such only in
3695             --  flag Fixed_Int is set to False.
3696
3697             if Is_Floating_Point_Type (Typ)
3698               or else (Is_Fixed_Point_Type (Typ) and then not Fixed_Int)
3699               or else Int_Real
3700             then
3701                Valr := Expr_Value_R (N);
3702
3703                if LB_Known and then Valr >= Expr_Value_R (Lo)
3704                  and then UB_Known and then Valr <= Expr_Value_R (Hi)
3705                then
3706                   return True;
3707                else
3708                   return False;
3709                end if;
3710
3711             else
3712                Val := Expr_Value (N);
3713
3714                if         LB_Known and then Val >= Expr_Value (Lo)
3715                  and then UB_Known and then Val <= Expr_Value (Hi)
3716                then
3717                   return True;
3718                else
3719                   return False;
3720                end if;
3721             end if;
3722          end;
3723       end if;
3724    end Is_In_Range;
3725
3726    -------------------
3727    -- Is_Null_Range --
3728    -------------------
3729
3730    function Is_Null_Range (Lo : Node_Id; Hi : Node_Id) return Boolean is
3731       Typ : constant Entity_Id := Etype (Lo);
3732
3733    begin
3734       if not Compile_Time_Known_Value (Lo)
3735         or else not Compile_Time_Known_Value (Hi)
3736       then
3737          return False;
3738       end if;
3739
3740       if Is_Discrete_Type (Typ) then
3741          return Expr_Value (Lo) > Expr_Value (Hi);
3742
3743       else
3744          pragma Assert (Is_Real_Type (Typ));
3745          return Expr_Value_R (Lo) > Expr_Value_R (Hi);
3746       end if;
3747    end Is_Null_Range;
3748
3749    -----------------------------
3750    -- Is_OK_Static_Expression --
3751    -----------------------------
3752
3753    function Is_OK_Static_Expression (N : Node_Id) return Boolean is
3754    begin
3755       return Is_Static_Expression (N)
3756         and then not Raises_Constraint_Error (N);
3757    end Is_OK_Static_Expression;
3758
3759    ------------------------
3760    -- Is_OK_Static_Range --
3761    ------------------------
3762
3763    --  A static range is a range whose bounds are static expressions, or a
3764    --  Range_Attribute_Reference equivalent to such a range (RM 4.9(26)).
3765    --  We have already converted range attribute references, so we get the
3766    --  "or" part of this rule without needing a special test.
3767
3768    function Is_OK_Static_Range (N : Node_Id) return Boolean is
3769    begin
3770       return Is_OK_Static_Expression (Low_Bound (N))
3771         and then Is_OK_Static_Expression (High_Bound (N));
3772    end Is_OK_Static_Range;
3773
3774    --------------------------
3775    -- Is_OK_Static_Subtype --
3776    --------------------------
3777
3778    --  Determines if Typ is a static subtype as defined in (RM 4.9(26))
3779    --  where neither bound raises constraint error when evaluated.
3780
3781    function Is_OK_Static_Subtype (Typ : Entity_Id) return Boolean is
3782       Base_T   : constant Entity_Id := Base_Type (Typ);
3783       Anc_Subt : Entity_Id;
3784
3785    begin
3786       --  First a quick check on the non static subtype flag. As described
3787       --  in further detail in Einfo, this flag is not decisive in all cases,
3788       --  but if it is set, then the subtype is definitely non-static.
3789
3790       if Is_Non_Static_Subtype (Typ) then
3791          return False;
3792       end if;
3793
3794       Anc_Subt := Ancestor_Subtype (Typ);
3795
3796       if Anc_Subt = Empty then
3797          Anc_Subt := Base_T;
3798       end if;
3799
3800       if Is_Generic_Type (Root_Type (Base_T))
3801         or else Is_Generic_Actual_Type (Base_T)
3802       then
3803          return False;
3804
3805       --  String types
3806
3807       elsif Is_String_Type (Typ) then
3808          return
3809            Ekind (Typ) = E_String_Literal_Subtype
3810              or else
3811            (Is_OK_Static_Subtype (Component_Type (Typ))
3812               and then Is_OK_Static_Subtype (Etype (First_Index (Typ))));
3813
3814       --  Scalar types
3815
3816       elsif Is_Scalar_Type (Typ) then
3817          if Base_T = Typ then
3818             return True;
3819
3820          else
3821             --  Scalar_Range (Typ) might be an N_Subtype_Indication, so
3822             --  use Get_Type_Low,High_Bound.
3823
3824             return     Is_OK_Static_Subtype (Anc_Subt)
3825               and then Is_OK_Static_Expression (Type_Low_Bound (Typ))
3826               and then Is_OK_Static_Expression (Type_High_Bound (Typ));
3827          end if;
3828
3829       --  Types other than string and scalar types are never static
3830
3831       else
3832          return False;
3833       end if;
3834    end Is_OK_Static_Subtype;
3835
3836    ---------------------
3837    -- Is_Out_Of_Range --
3838    ---------------------
3839
3840    function Is_Out_Of_Range
3841      (N            : Node_Id;
3842       Typ          : Entity_Id;
3843       Assume_Valid : Boolean := False;
3844       Fixed_Int    : Boolean := False;
3845       Int_Real     : Boolean := False) return Boolean
3846    is
3847       Val  : Uint;
3848       Valr : Ureal;
3849
3850       pragma Warnings (Off, Assume_Valid);
3851       --  For now Assume_Valid is unreferenced since the current implementation
3852       --  always returns False if N is not a compile time known value, but we
3853       --  keep the parameter to allow for future enhancements in which we try
3854       --  to get the information in the variable case as well.
3855
3856    begin
3857       --  Universal types have no range limits, so always in range
3858
3859       if Typ = Universal_Integer or else Typ = Universal_Real then
3860          return False;
3861
3862       --  Never out of range if not scalar type. Don't know if this can
3863       --  actually happen, but our spec allows it, so we must check!
3864
3865       elsif not Is_Scalar_Type (Typ) then
3866          return False;
3867
3868       --  Never out of range if this is a generic type, since the bounds
3869       --  of generic types are junk. Note that if we only checked for
3870       --  static expressions (instead of compile time known values) below,
3871       --  we would not need this check, because values of a generic type
3872       --  can never be static, but they can be known at compile time.
3873
3874       elsif Is_Generic_Type (Typ) then
3875          return False;
3876
3877       --  Never out of range unless we have a compile time known value
3878
3879       elsif not Compile_Time_Known_Value (N) then
3880          return False;
3881
3882       else
3883          declare
3884             Lo       : Node_Id;
3885             Hi       : Node_Id;
3886             LB_Known : Boolean;
3887             UB_Known : Boolean;
3888
3889          begin
3890             Lo := Type_Low_Bound (Typ);
3891             Hi := Type_High_Bound (Typ);
3892
3893             LB_Known := Compile_Time_Known_Value (Lo);
3894             UB_Known := Compile_Time_Known_Value (Hi);
3895
3896             --  Real types (note that fixed-point types are not treated
3897             --  as being of a real type if the flag Fixed_Int is set,
3898             --  since in that case they are regarded as integer types).
3899
3900             if Is_Floating_Point_Type (Typ)
3901               or else (Is_Fixed_Point_Type (Typ) and then not Fixed_Int)
3902               or else Int_Real
3903             then
3904                Valr := Expr_Value_R (N);
3905
3906                if LB_Known and then Valr < Expr_Value_R (Lo) then
3907                   return True;
3908
3909                elsif UB_Known and then Expr_Value_R (Hi) < Valr then
3910                   return True;
3911
3912                else
3913                   return False;
3914                end if;
3915
3916             else
3917                Val := Expr_Value (N);
3918
3919                if LB_Known and then Val < Expr_Value (Lo) then
3920                   return True;
3921
3922                elsif UB_Known and then Expr_Value (Hi) < Val then
3923                   return True;
3924
3925                else
3926                   return False;
3927                end if;
3928             end if;
3929          end;
3930       end if;
3931    end Is_Out_Of_Range;
3932
3933    ---------------------
3934    -- Is_Static_Range --
3935    ---------------------
3936
3937    --  A static range is a range whose bounds are static expressions, or a
3938    --  Range_Attribute_Reference equivalent to such a range (RM 4.9(26)).
3939    --  We have already converted range attribute references, so we get the
3940    --  "or" part of this rule without needing a special test.
3941
3942    function Is_Static_Range (N : Node_Id) return Boolean is
3943    begin
3944       return Is_Static_Expression (Low_Bound (N))
3945         and then Is_Static_Expression (High_Bound (N));
3946    end Is_Static_Range;
3947
3948    -----------------------
3949    -- Is_Static_Subtype --
3950    -----------------------
3951
3952    --  Determines if Typ is a static subtype as defined in (RM 4.9(26))
3953
3954    function Is_Static_Subtype (Typ : Entity_Id) return Boolean is
3955       Base_T   : constant Entity_Id := Base_Type (Typ);
3956       Anc_Subt : Entity_Id;
3957
3958    begin
3959       --  First a quick check on the non static subtype flag. As described
3960       --  in further detail in Einfo, this flag is not decisive in all cases,
3961       --  but if it is set, then the subtype is definitely non-static.
3962
3963       if Is_Non_Static_Subtype (Typ) then
3964          return False;
3965       end if;
3966
3967       Anc_Subt := Ancestor_Subtype (Typ);
3968
3969       if Anc_Subt = Empty then
3970          Anc_Subt := Base_T;
3971       end if;
3972
3973       if Is_Generic_Type (Root_Type (Base_T))
3974         or else Is_Generic_Actual_Type (Base_T)
3975       then
3976          return False;
3977
3978       --  String types
3979
3980       elsif Is_String_Type (Typ) then
3981          return
3982            Ekind (Typ) = E_String_Literal_Subtype
3983              or else
3984            (Is_Static_Subtype (Component_Type (Typ))
3985               and then Is_Static_Subtype (Etype (First_Index (Typ))));
3986
3987       --  Scalar types
3988
3989       elsif Is_Scalar_Type (Typ) then
3990          if Base_T = Typ then
3991             return True;
3992
3993          else
3994             return     Is_Static_Subtype (Anc_Subt)
3995               and then Is_Static_Expression (Type_Low_Bound (Typ))
3996               and then Is_Static_Expression (Type_High_Bound (Typ));
3997          end if;
3998
3999       --  Types other than string and scalar types are never static
4000
4001       else
4002          return False;
4003       end if;
4004    end Is_Static_Subtype;
4005
4006    --------------------
4007    -- Not_Null_Range --
4008    --------------------
4009
4010    function Not_Null_Range (Lo : Node_Id; Hi : Node_Id) return Boolean is
4011       Typ : constant Entity_Id := Etype (Lo);
4012
4013    begin
4014       if not Compile_Time_Known_Value (Lo)
4015         or else not Compile_Time_Known_Value (Hi)
4016       then
4017          return False;
4018       end if;
4019
4020       if Is_Discrete_Type (Typ) then
4021          return Expr_Value (Lo) <= Expr_Value (Hi);
4022
4023       else
4024          pragma Assert (Is_Real_Type (Typ));
4025
4026          return Expr_Value_R (Lo) <= Expr_Value_R (Hi);
4027       end if;
4028    end Not_Null_Range;
4029
4030    -------------
4031    -- OK_Bits --
4032    -------------
4033
4034    function OK_Bits (N : Node_Id; Bits : Uint) return Boolean is
4035    begin
4036       --  We allow a maximum of 500,000 bits which seems a reasonable limit
4037
4038       if Bits < 500_000 then
4039          return True;
4040
4041       else
4042          Error_Msg_N ("static value too large, capacity exceeded", N);
4043          return False;
4044       end if;
4045    end OK_Bits;
4046
4047    ------------------
4048    -- Out_Of_Range --
4049    ------------------
4050
4051    procedure Out_Of_Range (N : Node_Id) is
4052    begin
4053       --  If we have the static expression case, then this is an illegality
4054       --  in Ada 95 mode, except that in an instance, we never generate an
4055       --  error (if the error is legitimate, it was already diagnosed in
4056       --  the template). The expression to compute the length of a packed
4057       --  array is attached to the array type itself, and deserves a separate
4058       --  message.
4059
4060       if Is_Static_Expression (N)
4061         and then not In_Instance
4062         and then not In_Inlined_Body
4063         and then Ada_Version >= Ada_95
4064       then
4065          if Nkind (Parent (N)) = N_Defining_Identifier
4066            and then Is_Array_Type (Parent (N))
4067            and then Present (Packed_Array_Type (Parent (N)))
4068            and then Present (First_Rep_Item (Parent (N)))
4069          then
4070             Error_Msg_N
4071              ("length of packed array must not exceed Integer''Last",
4072               First_Rep_Item (Parent (N)));
4073             Rewrite (N, Make_Integer_Literal (Sloc (N), Uint_1));
4074
4075          else
4076             Apply_Compile_Time_Constraint_Error
4077               (N, "value not in range of}", CE_Range_Check_Failed);
4078          end if;
4079
4080       --  Here we generate a warning for the Ada 83 case, or when we are
4081       --  in an instance, or when we have a non-static expression case.
4082
4083       else
4084          Apply_Compile_Time_Constraint_Error
4085            (N, "value not in range of}?", CE_Range_Check_Failed);
4086       end if;
4087    end Out_Of_Range;
4088
4089    -------------------------
4090    -- Rewrite_In_Raise_CE --
4091    -------------------------
4092
4093    procedure Rewrite_In_Raise_CE (N : Node_Id; Exp : Node_Id) is
4094       Typ : constant Entity_Id := Etype (N);
4095
4096    begin
4097       --  If we want to raise CE in the condition of a raise_CE node
4098       --  we may as well get rid of the condition
4099
4100       if Present (Parent (N))
4101         and then Nkind (Parent (N)) = N_Raise_Constraint_Error
4102       then
4103          Set_Condition (Parent (N), Empty);
4104
4105       --  If the expression raising CE is a N_Raise_CE node, we can use
4106       --  that one. We just preserve the type of the context
4107
4108       elsif Nkind (Exp) = N_Raise_Constraint_Error then
4109          Rewrite (N, Exp);
4110          Set_Etype (N, Typ);
4111
4112       --  We have to build an explicit raise_ce node
4113
4114       else
4115          Rewrite (N,
4116            Make_Raise_Constraint_Error (Sloc (Exp),
4117              Reason => CE_Range_Check_Failed));
4118          Set_Raises_Constraint_Error (N);
4119          Set_Etype (N, Typ);
4120       end if;
4121    end Rewrite_In_Raise_CE;
4122
4123    ---------------------
4124    -- String_Type_Len --
4125    ---------------------
4126
4127    function String_Type_Len (Stype : Entity_Id) return Uint is
4128       NT : constant Entity_Id := Etype (First_Index (Stype));
4129       T  : Entity_Id;
4130
4131    begin
4132       if Is_OK_Static_Subtype (NT) then
4133          T := NT;
4134       else
4135          T := Base_Type (NT);
4136       end if;
4137
4138       return Expr_Value (Type_High_Bound (T)) -
4139              Expr_Value (Type_Low_Bound (T)) + 1;
4140    end String_Type_Len;
4141
4142    ------------------------------------
4143    -- Subtypes_Statically_Compatible --
4144    ------------------------------------
4145
4146    function Subtypes_Statically_Compatible
4147      (T1 : Entity_Id;
4148       T2 : Entity_Id) return Boolean
4149    is
4150    begin
4151       if Is_Scalar_Type (T1) then
4152
4153          --  Definitely compatible if we match
4154
4155          if Subtypes_Statically_Match (T1, T2) then
4156             return True;
4157
4158          --  If either subtype is nonstatic then they're not compatible
4159
4160          elsif not Is_Static_Subtype (T1)
4161            or else not Is_Static_Subtype (T2)
4162          then
4163             return False;
4164
4165          --  If either type has constraint error bounds, then consider that
4166          --  they match to avoid junk cascaded errors here.
4167
4168          elsif not Is_OK_Static_Subtype (T1)
4169            or else not Is_OK_Static_Subtype (T2)
4170          then
4171             return True;
4172
4173          --  Base types must match, but we don't check that (should
4174          --  we???) but we do at least check that both types are
4175          --  real, or both types are not real.
4176
4177          elsif Is_Real_Type (T1) /= Is_Real_Type (T2) then
4178             return False;
4179
4180          --  Here we check the bounds
4181
4182          else
4183             declare
4184                LB1 : constant Node_Id := Type_Low_Bound  (T1);
4185                HB1 : constant Node_Id := Type_High_Bound (T1);
4186                LB2 : constant Node_Id := Type_Low_Bound  (T2);
4187                HB2 : constant Node_Id := Type_High_Bound (T2);
4188
4189             begin
4190                if Is_Real_Type (T1) then
4191                   return
4192                     (Expr_Value_R (LB1) > Expr_Value_R (HB1))
4193                       or else
4194                     (Expr_Value_R (LB2) <= Expr_Value_R (LB1)
4195                        and then
4196                      Expr_Value_R (HB1) <= Expr_Value_R (HB2));
4197
4198                else
4199                   return
4200                     (Expr_Value (LB1) > Expr_Value (HB1))
4201                       or else
4202                     (Expr_Value (LB2) <= Expr_Value (LB1)
4203                        and then
4204                      Expr_Value (HB1) <= Expr_Value (HB2));
4205                end if;
4206             end;
4207          end if;
4208
4209       elsif Is_Access_Type (T1) then
4210          return not Is_Constrained (T2)
4211            or else Subtypes_Statically_Match
4212                      (Designated_Type (T1), Designated_Type (T2));
4213
4214       else
4215          return (Is_Composite_Type (T1) and then not Is_Constrained (T2))
4216            or else Subtypes_Statically_Match (T1, T2);
4217       end if;
4218    end Subtypes_Statically_Compatible;
4219
4220    -------------------------------
4221    -- Subtypes_Statically_Match --
4222    -------------------------------
4223
4224    --  Subtypes statically match if they have statically matching constraints
4225    --  (RM 4.9.1(2)). Constraints statically match if there are none, or if
4226    --  they are the same identical constraint, or if they are static and the
4227    --  values match (RM 4.9.1(1)).
4228
4229    function Subtypes_Statically_Match (T1, T2 : Entity_Id) return Boolean is
4230    begin
4231       --  A type always statically matches itself
4232
4233       if T1 = T2 then
4234          return True;
4235
4236       --  Scalar types
4237
4238       elsif Is_Scalar_Type (T1) then
4239
4240          --  Base types must be the same
4241
4242          if Base_Type (T1) /= Base_Type (T2) then
4243             return False;
4244          end if;
4245
4246          --  A constrained numeric subtype never matches an unconstrained
4247          --  subtype, i.e. both types must be constrained or unconstrained.
4248
4249          --  To understand the requirement for this test, see RM 4.9.1(1).
4250          --  As is made clear in RM 3.5.4(11), type Integer, for example
4251          --  is a constrained subtype with constraint bounds matching the
4252          --  bounds of its corresponding unconstrained base type. In this
4253          --  situation, Integer and Integer'Base do not statically match,
4254          --  even though they have the same bounds.
4255
4256          --  We only apply this test to types in Standard and types that
4257          --  appear in user programs. That way, we do not have to be
4258          --  too careful about setting Is_Constrained right for itypes.
4259
4260          if Is_Numeric_Type (T1)
4261            and then (Is_Constrained (T1) /= Is_Constrained (T2))
4262            and then (Scope (T1) = Standard_Standard
4263                       or else Comes_From_Source (T1))
4264            and then (Scope (T2) = Standard_Standard
4265                       or else Comes_From_Source (T2))
4266          then
4267             return False;
4268
4269          --  A generic scalar type does not statically match its base
4270          --  type (AI-311). In this case we make sure that the formals,
4271          --  which are first subtypes of their bases, are constrained.
4272
4273          elsif Is_Generic_Type (T1)
4274            and then Is_Generic_Type (T2)
4275            and then (Is_Constrained (T1) /= Is_Constrained (T2))
4276          then
4277             return False;
4278          end if;
4279
4280          --  If there was an error in either range, then just assume
4281          --  the types statically match to avoid further junk errors
4282
4283          if Error_Posted (Scalar_Range (T1))
4284               or else
4285             Error_Posted (Scalar_Range (T2))
4286          then
4287             return True;
4288          end if;
4289
4290          --  Otherwise both types have bound that can be compared
4291
4292          declare
4293             LB1 : constant Node_Id := Type_Low_Bound  (T1);
4294             HB1 : constant Node_Id := Type_High_Bound (T1);
4295             LB2 : constant Node_Id := Type_Low_Bound  (T2);
4296             HB2 : constant Node_Id := Type_High_Bound (T2);
4297
4298          begin
4299             --  If the bounds are the same tree node, then match
4300
4301             if LB1 = LB2 and then HB1 = HB2 then
4302                return True;
4303
4304             --  Otherwise bounds must be static and identical value
4305
4306             else
4307                if not Is_Static_Subtype (T1)
4308                  or else not Is_Static_Subtype (T2)
4309                then
4310                   return False;
4311
4312                --  If either type has constraint error bounds, then say
4313                --  that they match to avoid junk cascaded errors here.
4314
4315                elsif not Is_OK_Static_Subtype (T1)
4316                  or else not Is_OK_Static_Subtype (T2)
4317                then
4318                   return True;
4319
4320                elsif Is_Real_Type (T1) then
4321                   return
4322                     (Expr_Value_R (LB1) = Expr_Value_R (LB2))
4323                       and then
4324                     (Expr_Value_R (HB1) = Expr_Value_R (HB2));
4325
4326                else
4327                   return
4328                     Expr_Value (LB1) = Expr_Value (LB2)
4329                       and then
4330                     Expr_Value (HB1) = Expr_Value (HB2);
4331                end if;
4332             end if;
4333          end;
4334
4335       --  Type with discriminants
4336
4337       elsif Has_Discriminants (T1) or else Has_Discriminants (T2) then
4338
4339          --  Because of view exchanges in multiple instantiations, conformance
4340          --  checking might try to match a partial view of a type with no
4341          --  discriminants with a full view that has defaulted discriminants.
4342          --  In such a case, use the discriminant constraint of the full view,
4343          --  which must exist because we know that the two subtypes have the
4344          --  same base type.
4345
4346          if Has_Discriminants (T1) /= Has_Discriminants (T2) then
4347             if In_Instance then
4348                if Is_Private_Type (T2)
4349                  and then Present (Full_View (T2))
4350                  and then Has_Discriminants (Full_View (T2))
4351                then
4352                   return Subtypes_Statically_Match (T1, Full_View (T2));
4353
4354                elsif Is_Private_Type (T1)
4355                  and then Present (Full_View (T1))
4356                  and then Has_Discriminants (Full_View (T1))
4357                then
4358                   return Subtypes_Statically_Match (Full_View (T1), T2);
4359
4360                else
4361                   return False;
4362                end if;
4363             else
4364                return False;
4365             end if;
4366          end if;
4367
4368          declare
4369             DL1 : constant Elist_Id := Discriminant_Constraint (T1);
4370             DL2 : constant Elist_Id := Discriminant_Constraint (T2);
4371
4372             DA1 : Elmt_Id;
4373             DA2 : Elmt_Id;
4374
4375          begin
4376             if DL1 = DL2 then
4377                return True;
4378             elsif Is_Constrained (T1) /= Is_Constrained (T2) then
4379                return False;
4380             end if;
4381
4382             --  Now loop through the discriminant constraints
4383
4384             --  Note: the guard here seems necessary, since it is possible at
4385             --  least for DL1 to be No_Elist. Not clear this is reasonable ???
4386
4387             if Present (DL1) and then Present (DL2) then
4388                DA1 := First_Elmt (DL1);
4389                DA2 := First_Elmt (DL2);
4390                while Present (DA1) loop
4391                   declare
4392                      Expr1 : constant Node_Id := Node (DA1);
4393                      Expr2 : constant Node_Id := Node (DA2);
4394
4395                   begin
4396                      if not Is_Static_Expression (Expr1)
4397                        or else not Is_Static_Expression (Expr2)
4398                      then
4399                         return False;
4400
4401                         --  If either expression raised a constraint error,
4402                         --  consider the expressions as matching, since this
4403                         --  helps to prevent cascading errors.
4404
4405                      elsif Raises_Constraint_Error (Expr1)
4406                        or else Raises_Constraint_Error (Expr2)
4407                      then
4408                         null;
4409
4410                      elsif Expr_Value (Expr1) /= Expr_Value (Expr2) then
4411                         return False;
4412                      end if;
4413                   end;
4414
4415                   Next_Elmt (DA1);
4416                   Next_Elmt (DA2);
4417                end loop;
4418             end if;
4419          end;
4420
4421          return True;
4422
4423       --  A definite type does not match an indefinite or classwide type
4424       --  However, a generic type with unknown discriminants may be
4425       --  instantiated with a type with no discriminants, and conformance
4426       --  checking on an inherited operation may compare the actual with
4427       --  the subtype that renames it in the instance.
4428
4429       elsif
4430          Has_Unknown_Discriminants (T1) /= Has_Unknown_Discriminants (T2)
4431       then
4432          return
4433            Is_Generic_Actual_Type (T1) or else Is_Generic_Actual_Type (T2);
4434
4435       --  Array type
4436
4437       elsif Is_Array_Type (T1) then
4438
4439          --  If either subtype is unconstrained then both must be,
4440          --  and if both are unconstrained then no further checking
4441          --  is needed.
4442
4443          if not Is_Constrained (T1) or else not Is_Constrained (T2) then
4444             return not (Is_Constrained (T1) or else Is_Constrained (T2));
4445          end if;
4446
4447          --  Both subtypes are constrained, so check that the index
4448          --  subtypes statically match.
4449
4450          declare
4451             Index1 : Node_Id := First_Index (T1);
4452             Index2 : Node_Id := First_Index (T2);
4453
4454          begin
4455             while Present (Index1) loop
4456                if not
4457                  Subtypes_Statically_Match (Etype (Index1), Etype (Index2))
4458                then
4459                   return False;
4460                end if;
4461
4462                Next_Index (Index1);
4463                Next_Index (Index2);
4464             end loop;
4465
4466             return True;
4467          end;
4468
4469       elsif Is_Access_Type (T1) then
4470          if Can_Never_Be_Null (T1) /= Can_Never_Be_Null (T2) then
4471             return False;
4472
4473          elsif Ekind (T1) = E_Access_Subprogram_Type
4474            or else Ekind (T1) = E_Anonymous_Access_Subprogram_Type
4475          then
4476             return
4477               Subtype_Conformant
4478                 (Designated_Type (T1),
4479                  Designated_Type (T2));
4480          else
4481             return
4482               Subtypes_Statically_Match
4483                 (Designated_Type (T1),
4484                  Designated_Type (T2))
4485               and then Is_Access_Constant (T1) = Is_Access_Constant (T2);
4486          end if;
4487
4488       --  All other types definitely match
4489
4490       else
4491          return True;
4492       end if;
4493    end Subtypes_Statically_Match;
4494
4495    ----------
4496    -- Test --
4497    ----------
4498
4499    function Test (Cond : Boolean) return Uint is
4500    begin
4501       if Cond then
4502          return Uint_1;
4503       else
4504          return Uint_0;
4505       end if;
4506    end Test;
4507
4508    ---------------------------------
4509    -- Test_Expression_Is_Foldable --
4510    ---------------------------------
4511
4512    --  One operand case
4513
4514    procedure Test_Expression_Is_Foldable
4515      (N    : Node_Id;
4516       Op1  : Node_Id;
4517       Stat : out Boolean;
4518       Fold : out Boolean)
4519    is
4520    begin
4521       Stat := False;
4522       Fold := False;
4523
4524       if Debug_Flag_Dot_F and then In_Extended_Main_Source_Unit (N) then
4525          return;
4526       end if;
4527
4528       --  If operand is Any_Type, just propagate to result and do not
4529       --  try to fold, this prevents cascaded errors.
4530
4531       if Etype (Op1) = Any_Type then
4532          Set_Etype (N, Any_Type);
4533          return;
4534
4535       --  If operand raises constraint error, then replace node N with the
4536       --  raise constraint error node, and we are obviously not foldable.
4537       --  Note that this replacement inherits the Is_Static_Expression flag
4538       --  from the operand.
4539
4540       elsif Raises_Constraint_Error (Op1) then
4541          Rewrite_In_Raise_CE (N, Op1);
4542          return;
4543
4544       --  If the operand is not static, then the result is not static, and
4545       --  all we have to do is to check the operand since it is now known
4546       --  to appear in a non-static context.
4547
4548       elsif not Is_Static_Expression (Op1) then
4549          Check_Non_Static_Context (Op1);
4550          Fold := Compile_Time_Known_Value (Op1);
4551          return;
4552
4553       --   An expression of a formal modular type is not foldable because
4554       --   the modulus is unknown.
4555
4556       elsif Is_Modular_Integer_Type (Etype (Op1))
4557         and then Is_Generic_Type (Etype (Op1))
4558       then
4559          Check_Non_Static_Context (Op1);
4560          return;
4561
4562       --  Here we have the case of an operand whose type is OK, which is
4563       --  static, and which does not raise constraint error, we can fold.
4564
4565       else
4566          Set_Is_Static_Expression (N);
4567          Fold := True;
4568          Stat := True;
4569       end if;
4570    end Test_Expression_Is_Foldable;
4571
4572    --  Two operand case
4573
4574    procedure Test_Expression_Is_Foldable
4575      (N    : Node_Id;
4576       Op1  : Node_Id;
4577       Op2  : Node_Id;
4578       Stat : out Boolean;
4579       Fold : out Boolean)
4580    is
4581       Rstat : constant Boolean := Is_Static_Expression (Op1)
4582                                     and then Is_Static_Expression (Op2);
4583
4584    begin
4585       Stat := False;
4586       Fold := False;
4587
4588       if Debug_Flag_Dot_F and then In_Extended_Main_Source_Unit (N) then
4589          return;
4590       end if;
4591
4592       --  If either operand is Any_Type, just propagate to result and
4593       --  do not try to fold, this prevents cascaded errors.
4594
4595       if Etype (Op1) = Any_Type or else Etype (Op2) = Any_Type then
4596          Set_Etype (N, Any_Type);
4597          return;
4598
4599       --  If left operand raises constraint error, then replace node N with
4600       --  the raise constraint error node, and we are obviously not foldable.
4601       --  Is_Static_Expression is set from the two operands in the normal way,
4602       --  and we check the right operand if it is in a non-static context.
4603
4604       elsif Raises_Constraint_Error (Op1) then
4605          if not Rstat then
4606             Check_Non_Static_Context (Op2);
4607          end if;
4608
4609          Rewrite_In_Raise_CE (N, Op1);
4610          Set_Is_Static_Expression (N, Rstat);
4611          return;
4612
4613       --  Similar processing for the case of the right operand. Note that
4614       --  we don't use this routine for the short-circuit case, so we do
4615       --  not have to worry about that special case here.
4616
4617       elsif Raises_Constraint_Error (Op2) then
4618          if not Rstat then
4619             Check_Non_Static_Context (Op1);
4620          end if;
4621
4622          Rewrite_In_Raise_CE (N, Op2);
4623          Set_Is_Static_Expression (N, Rstat);
4624          return;
4625
4626       --  Exclude expressions of a generic modular type, as above
4627
4628       elsif Is_Modular_Integer_Type (Etype (Op1))
4629         and then Is_Generic_Type (Etype (Op1))
4630       then
4631          Check_Non_Static_Context (Op1);
4632          return;
4633
4634       --  If result is not static, then check non-static contexts on operands
4635       --  since one of them may be static and the other one may not be static
4636
4637       elsif not Rstat then
4638          Check_Non_Static_Context (Op1);
4639          Check_Non_Static_Context (Op2);
4640          Fold := Compile_Time_Known_Value (Op1)
4641                    and then Compile_Time_Known_Value (Op2);
4642          return;
4643
4644       --  Else result is static and foldable. Both operands are static,
4645       --  and neither raises constraint error, so we can definitely fold.
4646
4647       else
4648          Set_Is_Static_Expression (N);
4649          Fold := True;
4650          Stat := True;
4651          return;
4652       end if;
4653    end Test_Expression_Is_Foldable;
4654
4655    --------------
4656    -- To_Bits --
4657    --------------
4658
4659    procedure To_Bits (U : Uint; B : out Bits) is
4660    begin
4661       for J in 0 .. B'Last loop
4662          B (J) := (U / (2 ** J)) mod 2 /= 0;
4663       end loop;
4664    end To_Bits;
4665
4666    --------------------
4667    -- Why_Not_Static --
4668    --------------------
4669
4670    procedure Why_Not_Static (Expr : Node_Id) is
4671       N   : constant Node_Id   := Original_Node (Expr);
4672       Typ : Entity_Id;
4673       E   : Entity_Id;
4674
4675       procedure Why_Not_Static_List (L : List_Id);
4676       --  A version that can be called on a list of expressions. Finds
4677       --  all non-static violations in any element of the list.
4678
4679       -------------------------
4680       -- Why_Not_Static_List --
4681       -------------------------
4682
4683       procedure Why_Not_Static_List (L : List_Id) is
4684          N : Node_Id;
4685
4686       begin
4687          if Is_Non_Empty_List (L) then
4688             N := First (L);
4689             while Present (N) loop
4690                Why_Not_Static (N);
4691                Next (N);
4692             end loop;
4693          end if;
4694       end Why_Not_Static_List;
4695
4696    --  Start of processing for Why_Not_Static
4697
4698    begin
4699       --  If in ACATS mode (debug flag 2), then suppress all these
4700       --  messages, this avoids massive updates to the ACATS base line.
4701
4702       if Debug_Flag_2 then
4703          return;
4704       end if;
4705
4706       --  Ignore call on error or empty node
4707
4708       if No (Expr) or else Nkind (Expr) = N_Error then
4709          return;
4710       end if;
4711
4712       --  Preprocessing for sub expressions
4713
4714       if Nkind (Expr) in N_Subexpr then
4715
4716          --  Nothing to do if expression is static
4717
4718          if Is_OK_Static_Expression (Expr) then
4719             return;
4720          end if;
4721
4722          --  Test for constraint error raised
4723
4724          if Raises_Constraint_Error (Expr) then
4725             Error_Msg_N
4726               ("expression raises exception, cannot be static " &
4727                "(RM 4.9(34))!", N);
4728             return;
4729          end if;
4730
4731          --  If no type, then something is pretty wrong, so ignore
4732
4733          Typ := Etype (Expr);
4734
4735          if No (Typ) then
4736             return;
4737          end if;
4738
4739          --  Type must be scalar or string type
4740
4741          if not Is_Scalar_Type (Typ)
4742            and then not Is_String_Type (Typ)
4743          then
4744             Error_Msg_N
4745               ("static expression must have scalar or string type " &
4746                "(RM 4.9(2))!", N);
4747             return;
4748          end if;
4749       end if;
4750
4751       --  If we got through those checks, test particular node kind
4752
4753       case Nkind (N) is
4754          when N_Expanded_Name | N_Identifier | N_Operator_Symbol =>
4755             E := Entity (N);
4756
4757             if Is_Named_Number (E) then
4758                null;
4759
4760             elsif Ekind (E) = E_Constant then
4761                if not Is_Static_Expression (Constant_Value (E)) then
4762                   Error_Msg_NE
4763                     ("& is not a static constant (RM 4.9(5))!", N, E);
4764                end if;
4765
4766             else
4767                Error_Msg_NE
4768                  ("& is not static constant or named number " &
4769                   "(RM 4.9(5))!", N, E);
4770             end if;
4771
4772          when N_Binary_Op | N_And_Then | N_Or_Else | N_Membership_Test =>
4773             if Nkind (N) in N_Op_Shift then
4774                Error_Msg_N
4775                 ("shift functions are never static (RM 4.9(6,18))!", N);
4776
4777             else
4778                Why_Not_Static (Left_Opnd (N));
4779                Why_Not_Static (Right_Opnd (N));
4780             end if;
4781
4782          when N_Unary_Op =>
4783             Why_Not_Static (Right_Opnd (N));
4784
4785          when N_Attribute_Reference =>
4786             Why_Not_Static_List (Expressions (N));
4787
4788             E := Etype (Prefix (N));
4789
4790             if E = Standard_Void_Type then
4791                return;
4792             end if;
4793
4794             --  Special case non-scalar'Size since this is a common error
4795
4796             if Attribute_Name (N) = Name_Size then
4797                Error_Msg_N
4798                  ("size attribute is only static for scalar type " &
4799                   "(RM 4.9(7,8))", N);
4800
4801             --  Flag array cases
4802
4803             elsif Is_Array_Type (E) then
4804                if Attribute_Name (N) /= Name_First
4805                     and then
4806                   Attribute_Name (N) /= Name_Last
4807                     and then
4808                   Attribute_Name (N) /= Name_Length
4809                then
4810                   Error_Msg_N
4811                     ("static array attribute must be Length, First, or Last " &
4812                      "(RM 4.9(8))!", N);
4813
4814                --  Since we know the expression is not-static (we already
4815                --  tested for this, must mean array is not static).
4816
4817                else
4818                   Error_Msg_N
4819                     ("prefix is non-static array (RM 4.9(8))!", Prefix (N));
4820                end if;
4821
4822                return;
4823
4824             --  Special case generic types, since again this is a common
4825             --  source of confusion.
4826
4827             elsif Is_Generic_Actual_Type (E)
4828                     or else
4829                   Is_Generic_Type (E)
4830             then
4831                Error_Msg_N
4832                  ("attribute of generic type is never static " &
4833                   "(RM 4.9(7,8))!", N);
4834
4835             elsif Is_Static_Subtype (E) then
4836                null;
4837
4838             elsif Is_Scalar_Type (E) then
4839                Error_Msg_N
4840                  ("prefix type for attribute is not static scalar subtype " &
4841                   "(RM 4.9(7))!", N);
4842
4843             else
4844                Error_Msg_N
4845                  ("static attribute must apply to array/scalar type " &
4846                   "(RM 4.9(7,8))!", N);
4847             end if;
4848
4849          when N_String_Literal =>
4850             Error_Msg_N
4851               ("subtype of string literal is non-static (RM 4.9(4))!", N);
4852
4853          when N_Explicit_Dereference =>
4854             Error_Msg_N
4855               ("explicit dereference is never static (RM 4.9)!", N);
4856
4857          when N_Function_Call =>
4858             Why_Not_Static_List (Parameter_Associations (N));
4859             Error_Msg_N ("non-static function call (RM 4.9(6,18))!", N);
4860
4861          when N_Parameter_Association =>
4862             Why_Not_Static (Explicit_Actual_Parameter (N));
4863
4864          when N_Indexed_Component =>
4865             Error_Msg_N
4866               ("indexed component is never static (RM 4.9)!", N);
4867
4868          when N_Procedure_Call_Statement =>
4869             Error_Msg_N
4870               ("procedure call is never static (RM 4.9)!", N);
4871
4872          when N_Qualified_Expression =>
4873             Why_Not_Static (Expression (N));
4874
4875          when N_Aggregate | N_Extension_Aggregate =>
4876             Error_Msg_N
4877               ("an aggregate is never static (RM 4.9)!", N);
4878
4879          when N_Range =>
4880             Why_Not_Static (Low_Bound (N));
4881             Why_Not_Static (High_Bound (N));
4882
4883          when N_Range_Constraint =>
4884             Why_Not_Static (Range_Expression (N));
4885
4886          when N_Subtype_Indication =>
4887             Why_Not_Static (Constraint (N));
4888
4889          when N_Selected_Component =>
4890             Error_Msg_N
4891               ("selected component is never static (RM 4.9)!", N);
4892
4893          when N_Slice =>
4894             Error_Msg_N
4895               ("slice is never static (RM 4.9)!", N);
4896
4897          when N_Type_Conversion =>
4898             Why_Not_Static (Expression (N));
4899
4900             if not Is_Scalar_Type (Etype (Prefix (N)))
4901               or else not Is_Static_Subtype (Etype (Prefix (N)))
4902             then
4903                Error_Msg_N
4904                  ("static conversion requires static scalar subtype result " &
4905                   "(RM 4.9(9))!", N);
4906             end if;
4907
4908          when N_Unchecked_Type_Conversion =>
4909             Error_Msg_N
4910               ("unchecked type conversion is never static (RM 4.9)!", N);
4911
4912          when others =>
4913             null;
4914
4915       end case;
4916    end Why_Not_Static;
4917
4918 end Sem_Eval;