OSDN Git Service

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