OSDN Git Service

2006-10-31 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_util.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ U T I L                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2006, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Elists;   use Elists;
32 with Errout;   use Errout;
33 with Exp_Aggr; use Exp_Aggr;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Hostparm; use Hostparm;
36 with Inline;   use Inline;
37 with Itypes;   use Itypes;
38 with Lib;      use Lib;
39 with Namet;    use Namet;
40 with Nlists;   use Nlists;
41 with Nmake;    use Nmake;
42 with Opt;      use Opt;
43 with Restrict; use Restrict;
44 with Rident;   use Rident;
45 with Sem;      use Sem;
46 with Sem_Ch8;  use Sem_Ch8;
47 with Sem_Eval; use Sem_Eval;
48 with Sem_Res;  use Sem_Res;
49 with Sem_Type; use Sem_Type;
50 with Sem_Util; use Sem_Util;
51 with Snames;   use Snames;
52 with Stand;    use Stand;
53 with Stringt;  use Stringt;
54 with Targparm; use Targparm;
55 with Tbuild;   use Tbuild;
56 with Ttypes;   use Ttypes;
57 with Uintp;    use Uintp;
58 with Urealp;   use Urealp;
59 with Validsw;  use Validsw;
60
61 package body Exp_Util is
62
63    -----------------------
64    -- Local Subprograms --
65    -----------------------
66
67    function Build_Task_Array_Image
68      (Loc    : Source_Ptr;
69       Id_Ref : Node_Id;
70       A_Type : Entity_Id;
71       Dyn    : Boolean := False) return Node_Id;
72    --  Build function to generate the image string for a task that is an
73    --  array component, concatenating the images of each index. To avoid
74    --  storage leaks, the string is built with successive slice assignments.
75    --  The flag Dyn indicates whether this is called for the initialization
76    --  procedure of an array of tasks, or for the name of a dynamically
77    --  created task that is assigned to an indexed component.
78
79    function Build_Task_Image_Function
80      (Loc   : Source_Ptr;
81       Decls : List_Id;
82       Stats : List_Id;
83       Res   : Entity_Id) return Node_Id;
84    --  Common processing for Task_Array_Image and Task_Record_Image.
85    --  Build function body that computes image.
86
87    procedure Build_Task_Image_Prefix
88       (Loc    : Source_Ptr;
89        Len    : out Entity_Id;
90        Res    : out Entity_Id;
91        Pos    : out Entity_Id;
92        Prefix : Entity_Id;
93        Sum    : Node_Id;
94        Decls  : in out List_Id;
95        Stats  : in out List_Id);
96    --  Common processing for Task_Array_Image and Task_Record_Image.
97    --  Create local variables and assign prefix of name to result string.
98
99    function Build_Task_Record_Image
100      (Loc    : Source_Ptr;
101       Id_Ref : Node_Id;
102       Dyn    : Boolean := False) return Node_Id;
103    --  Build function to generate the image string for a task that is a
104    --  record component. Concatenate name of variable with that of selector.
105    --  The flag Dyn indicates whether this is called for the initialization
106    --  procedure of record with task components, or for a dynamically
107    --  created task that is assigned to a selected component.
108
109    function Make_CW_Equivalent_Type
110      (T : Entity_Id;
111       E : Node_Id) return Entity_Id;
112    --  T is a class-wide type entity, E is the initial expression node that
113    --  constrains T in case such as: " X: T := E" or "new T'(E)"
114    --  This function returns the entity of the Equivalent type and inserts
115    --  on the fly the necessary declaration such as:
116    --
117    --    type anon is record
118    --       _parent : Root_Type (T); constrained with E discriminants (if any)
119    --       Extension : String (1 .. expr to match size of E);
120    --    end record;
121    --
122    --  This record is compatible with any object of the class of T thanks
123    --  to the first field and has the same size as E thanks to the second.
124
125    function Make_Literal_Range
126      (Loc         : Source_Ptr;
127       Literal_Typ : Entity_Id) return Node_Id;
128    --  Produce a Range node whose bounds are:
129    --    Low_Bound (Literal_Type) ..
130    --        Low_Bound (Literal_Type) + Length (Literal_Typ) - 1
131    --  this is used for expanding declarations like X : String := "sdfgdfg";
132
133    function New_Class_Wide_Subtype
134      (CW_Typ : Entity_Id;
135       N      : Node_Id) return Entity_Id;
136    --  Create an implicit subtype of CW_Typ attached to node N
137
138    ----------------------
139    -- Adjust_Condition --
140    ----------------------
141
142    procedure Adjust_Condition (N : Node_Id) is
143    begin
144       if No (N) then
145          return;
146       end if;
147
148       declare
149          Loc : constant Source_Ptr := Sloc (N);
150          T   : constant Entity_Id  := Etype (N);
151          Ti  : Entity_Id;
152
153       begin
154          --  For now, we simply ignore a call where the argument has no
155          --  type (probably case of unanalyzed condition), or has a type
156          --  that is not Boolean. This is because this is a pretty marginal
157          --  piece of functionality, and violations of these rules are
158          --  likely to be truly marginal (how much code uses Fortran Logical
159          --  as the barrier to a protected entry?) and we do not want to
160          --  blow up existing programs. We can change this to an assertion
161          --  after 3.12a is released ???
162
163          if No (T) or else not Is_Boolean_Type (T) then
164             return;
165          end if;
166
167          --  Apply validity checking if needed
168
169          if Validity_Checks_On and Validity_Check_Tests then
170             Ensure_Valid (N);
171          end if;
172
173          --  Immediate return if standard boolean, the most common case,
174          --  where nothing needs to be done.
175
176          if Base_Type (T) = Standard_Boolean then
177             return;
178          end if;
179
180          --  Case of zero/non-zero semantics or non-standard enumeration
181          --  representation. In each case, we rewrite the node as:
182
183          --      ityp!(N) /= False'Enum_Rep
184
185          --  where ityp is an integer type with large enough size to hold
186          --  any value of type T.
187
188          if Nonzero_Is_True (T) or else Has_Non_Standard_Rep (T) then
189             if Esize (T) <= Esize (Standard_Integer) then
190                Ti := Standard_Integer;
191             else
192                Ti := Standard_Long_Long_Integer;
193             end if;
194
195             Rewrite (N,
196               Make_Op_Ne (Loc,
197                 Left_Opnd  => Unchecked_Convert_To (Ti, N),
198                 Right_Opnd =>
199                   Make_Attribute_Reference (Loc,
200                     Attribute_Name => Name_Enum_Rep,
201                     Prefix         =>
202                       New_Occurrence_Of (First_Literal (T), Loc))));
203             Analyze_And_Resolve (N, Standard_Boolean);
204
205          else
206             Rewrite (N, Convert_To (Standard_Boolean, N));
207             Analyze_And_Resolve (N, Standard_Boolean);
208          end if;
209       end;
210    end Adjust_Condition;
211
212    ------------------------
213    -- Adjust_Result_Type --
214    ------------------------
215
216    procedure Adjust_Result_Type (N : Node_Id; T : Entity_Id) is
217    begin
218       --  Ignore call if current type is not Standard.Boolean
219
220       if Etype (N) /= Standard_Boolean then
221          return;
222       end if;
223
224       --  If result is already of correct type, nothing to do. Note that
225       --  this will get the most common case where everything has a type
226       --  of Standard.Boolean.
227
228       if Base_Type (T) = Standard_Boolean then
229          return;
230
231       else
232          declare
233             KP : constant Node_Kind := Nkind (Parent (N));
234
235          begin
236             --  If result is to be used as a Condition in the syntax, no need
237             --  to convert it back, since if it was changed to Standard.Boolean
238             --  using Adjust_Condition, that is just fine for this usage.
239
240             if KP in N_Raise_xxx_Error or else KP in N_Has_Condition then
241                return;
242
243             --  If result is an operand of another logical operation, no need
244             --  to reset its type, since Standard.Boolean is just fine, and
245             --  such operations always do Adjust_Condition on their operands.
246
247             elsif KP in N_Op_Boolean
248               or else KP = N_And_Then
249               or else KP = N_Or_Else
250               or else KP = N_Op_Not
251             then
252                return;
253
254             --  Otherwise we perform a conversion from the current type,
255             --  which must be Standard.Boolean, to the desired type.
256
257             else
258                Set_Analyzed (N);
259                Rewrite (N, Convert_To (T, N));
260                Analyze_And_Resolve (N, T);
261             end if;
262          end;
263       end if;
264    end Adjust_Result_Type;
265
266    --------------------------
267    -- Append_Freeze_Action --
268    --------------------------
269
270    procedure Append_Freeze_Action (T : Entity_Id; N : Node_Id) is
271       Fnode : Node_Id;
272
273    begin
274       Ensure_Freeze_Node (T);
275       Fnode := Freeze_Node (T);
276
277       if No (Actions (Fnode)) then
278          Set_Actions (Fnode, New_List);
279       end if;
280
281       Append (N, Actions (Fnode));
282    end Append_Freeze_Action;
283
284    ---------------------------
285    -- Append_Freeze_Actions --
286    ---------------------------
287
288    procedure Append_Freeze_Actions (T : Entity_Id; L : List_Id) is
289       Fnode : constant Node_Id := Freeze_Node (T);
290
291    begin
292       if No (L) then
293          return;
294
295       else
296          if No (Actions (Fnode)) then
297             Set_Actions (Fnode, L);
298
299          else
300             Append_List (L, Actions (Fnode));
301          end if;
302
303       end if;
304    end Append_Freeze_Actions;
305
306    ------------------------
307    -- Build_Runtime_Call --
308    ------------------------
309
310    function Build_Runtime_Call (Loc : Source_Ptr; RE : RE_Id) return Node_Id is
311    begin
312       --  If entity is not available, we can skip making the call (this avoids
313       --  junk duplicated error messages in a number of cases).
314
315       if not RTE_Available (RE) then
316          return Make_Null_Statement (Loc);
317       else
318          return
319            Make_Procedure_Call_Statement (Loc,
320              Name => New_Reference_To (RTE (RE), Loc));
321       end if;
322    end Build_Runtime_Call;
323
324    ----------------------------
325    -- Build_Task_Array_Image --
326    ----------------------------
327
328    --  This function generates the body for a function that constructs the
329    --  image string for a task that is an array component. The function is
330    --  local to the init proc for the array type, and is called for each one
331    --  of the components. The constructed image has the form of an indexed
332    --  component, whose prefix is the outer variable of the array type.
333    --  The n-dimensional array type has known indices Index, Index2...
334    --  Id_Ref is an indexed component form created by the enclosing init proc.
335    --  Its successive indices are Val1, Val2,.. which are the loop variables
336    --  in the loops that call the individual task init proc on each component.
337
338    --  The generated function has the following structure:
339
340    --  function F return String is
341    --     Pref : string renames Task_Name;
342    --     T1   : String := Index1'Image (Val1);
343    --     ...
344    --     Tn   : String := indexn'image (Valn);
345    --     Len  : Integer := T1'Length + ... + Tn'Length + n + 1;
346    --     --  Len includes commas and the end parentheses.
347    --     Res  : String (1..Len);
348    --     Pos  : Integer := Pref'Length;
349    --
350    --  begin
351    --     Res (1 .. Pos) := Pref;
352    --     Pos := Pos + 1;
353    --     Res (Pos)    := '(';
354    --     Pos := Pos + 1;
355    --     Res (Pos .. Pos + T1'Length - 1) := T1;
356    --     Pos := Pos + T1'Length;
357    --     Res (Pos) := '.';
358    --     Pos := Pos + 1;
359    --     ...
360    --     Res (Pos .. Pos + Tn'Length - 1) := Tn;
361    --     Res (Len) := ')';
362    --
363    --     return Res;
364    --  end F;
365    --
366    --  Needless to say, multidimensional arrays of tasks are rare enough
367    --  that the bulkiness of this code is not really a concern.
368
369    function Build_Task_Array_Image
370      (Loc    : Source_Ptr;
371       Id_Ref : Node_Id;
372       A_Type : Entity_Id;
373       Dyn    : Boolean := False) return Node_Id
374    is
375       Dims : constant Nat := Number_Dimensions (A_Type);
376       --  Number of dimensions for array of tasks
377
378       Temps : array (1 .. Dims) of Entity_Id;
379       --  Array of temporaries to hold string for each index
380
381       Indx : Node_Id;
382       --  Index expression
383
384       Len : Entity_Id;
385       --  Total length of generated name
386
387       Pos : Entity_Id;
388       --  Running index for substring assignments
389
390       Pref : Entity_Id;
391       --  Name of enclosing variable, prefix of resulting name
392
393       Res : Entity_Id;
394       --  String to hold result
395
396       Val : Node_Id;
397       --  Value of successive indices
398
399       Sum : Node_Id;
400       --  Expression to compute total size of string
401
402       T : Entity_Id;
403       --  Entity for name at one index position
404
405       Decls : List_Id := New_List;
406       Stats : List_Id := New_List;
407
408    begin
409       Pref := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
410
411       --  For a dynamic task, the name comes from the target variable.
412       --  For a static one it is a formal of the enclosing init proc.
413
414       if Dyn then
415          Get_Name_String (Chars (Entity (Prefix (Id_Ref))));
416          Append_To (Decls,
417            Make_Object_Declaration (Loc,
418              Defining_Identifier => Pref,
419              Object_Definition => New_Occurrence_Of (Standard_String, Loc),
420              Expression =>
421                Make_String_Literal (Loc,
422                  Strval => String_From_Name_Buffer)));
423
424       else
425          Append_To (Decls,
426            Make_Object_Renaming_Declaration (Loc,
427              Defining_Identifier => Pref,
428              Subtype_Mark        => New_Occurrence_Of (Standard_String, Loc),
429              Name                => Make_Identifier (Loc, Name_uTask_Name)));
430       end if;
431
432       Indx := First_Index (A_Type);
433       Val  := First (Expressions (Id_Ref));
434
435       for J in 1 .. Dims loop
436          T := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
437          Temps (J) := T;
438
439          Append_To (Decls,
440             Make_Object_Declaration (Loc,
441                Defining_Identifier => T,
442                Object_Definition => New_Occurrence_Of (Standard_String, Loc),
443                Expression =>
444                  Make_Attribute_Reference (Loc,
445                    Attribute_Name => Name_Image,
446                    Prefix =>
447                      New_Occurrence_Of (Etype (Indx), Loc),
448                    Expressions => New_List (
449                      New_Copy_Tree (Val)))));
450
451          Next_Index (Indx);
452          Next (Val);
453       end loop;
454
455       Sum := Make_Integer_Literal (Loc, Dims + 1);
456
457       Sum :=
458         Make_Op_Add (Loc,
459           Left_Opnd => Sum,
460           Right_Opnd =>
461            Make_Attribute_Reference (Loc,
462              Attribute_Name => Name_Length,
463              Prefix =>
464                New_Occurrence_Of (Pref, Loc),
465              Expressions => New_List (Make_Integer_Literal (Loc, 1))));
466
467       for J in 1 .. Dims loop
468          Sum :=
469             Make_Op_Add (Loc,
470              Left_Opnd => Sum,
471              Right_Opnd =>
472               Make_Attribute_Reference (Loc,
473                 Attribute_Name => Name_Length,
474                 Prefix =>
475                   New_Occurrence_Of (Temps (J), Loc),
476                 Expressions => New_List (Make_Integer_Literal (Loc, 1))));
477       end loop;
478
479       Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats);
480
481       Set_Character_Literal_Name (Char_Code (Character'Pos ('(')));
482
483       Append_To (Stats,
484          Make_Assignment_Statement (Loc,
485            Name => Make_Indexed_Component (Loc,
486               Prefix => New_Occurrence_Of (Res, Loc),
487               Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
488            Expression =>
489              Make_Character_Literal (Loc,
490                Chars => Name_Find,
491                Char_Literal_Value =>
492                  UI_From_Int (Character'Pos ('(')))));
493
494       Append_To (Stats,
495          Make_Assignment_Statement (Loc,
496             Name => New_Occurrence_Of (Pos, Loc),
497             Expression =>
498               Make_Op_Add (Loc,
499                 Left_Opnd => New_Occurrence_Of (Pos, Loc),
500                 Right_Opnd => Make_Integer_Literal (Loc, 1))));
501
502       for J in 1 .. Dims loop
503
504          Append_To (Stats,
505             Make_Assignment_Statement (Loc,
506               Name => Make_Slice (Loc,
507                  Prefix => New_Occurrence_Of (Res, Loc),
508                  Discrete_Range  =>
509                    Make_Range (Loc,
510                       Low_Bound => New_Occurrence_Of  (Pos, Loc),
511                       High_Bound => Make_Op_Subtract (Loc,
512                         Left_Opnd =>
513                           Make_Op_Add (Loc,
514                             Left_Opnd => New_Occurrence_Of (Pos, Loc),
515                             Right_Opnd =>
516                               Make_Attribute_Reference (Loc,
517                                 Attribute_Name => Name_Length,
518                                 Prefix =>
519                                   New_Occurrence_Of (Temps (J), Loc),
520                                 Expressions =>
521                                   New_List (Make_Integer_Literal (Loc, 1)))),
522                          Right_Opnd => Make_Integer_Literal (Loc, 1)))),
523
524               Expression => New_Occurrence_Of (Temps (J), Loc)));
525
526          if J < Dims then
527             Append_To (Stats,
528                Make_Assignment_Statement (Loc,
529                   Name => New_Occurrence_Of (Pos, Loc),
530                   Expression =>
531                     Make_Op_Add (Loc,
532                       Left_Opnd => New_Occurrence_Of (Pos, Loc),
533                       Right_Opnd =>
534                         Make_Attribute_Reference (Loc,
535                           Attribute_Name => Name_Length,
536                             Prefix => New_Occurrence_Of (Temps (J), Loc),
537                             Expressions =>
538                               New_List (Make_Integer_Literal (Loc, 1))))));
539
540             Set_Character_Literal_Name (Char_Code (Character'Pos (',')));
541
542             Append_To (Stats,
543                Make_Assignment_Statement (Loc,
544                  Name => Make_Indexed_Component (Loc,
545                     Prefix => New_Occurrence_Of (Res, Loc),
546                     Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
547                  Expression =>
548                    Make_Character_Literal (Loc,
549                      Chars => Name_Find,
550                      Char_Literal_Value =>
551                        UI_From_Int (Character'Pos (',')))));
552
553             Append_To (Stats,
554               Make_Assignment_Statement (Loc,
555                 Name => New_Occurrence_Of (Pos, Loc),
556                   Expression =>
557                     Make_Op_Add (Loc,
558                       Left_Opnd => New_Occurrence_Of (Pos, Loc),
559                       Right_Opnd => Make_Integer_Literal (Loc, 1))));
560          end if;
561       end loop;
562
563       Set_Character_Literal_Name (Char_Code (Character'Pos (')')));
564
565       Append_To (Stats,
566          Make_Assignment_Statement (Loc,
567            Name => Make_Indexed_Component (Loc,
568               Prefix => New_Occurrence_Of (Res, Loc),
569               Expressions => New_List (New_Occurrence_Of (Len, Loc))),
570            Expression =>
571              Make_Character_Literal (Loc,
572                Chars => Name_Find,
573                Char_Literal_Value =>
574                  UI_From_Int (Character'Pos (')')))));
575       return Build_Task_Image_Function (Loc, Decls, Stats, Res);
576    end Build_Task_Array_Image;
577
578    ----------------------------
579    -- Build_Task_Image_Decls --
580    ----------------------------
581
582    function Build_Task_Image_Decls
583      (Loc          : Source_Ptr;
584       Id_Ref       : Node_Id;
585       A_Type       : Entity_Id;
586       In_Init_Proc : Boolean := False) return List_Id
587    is
588       Decls  : constant List_Id   := New_List;
589       T_Id   : Entity_Id := Empty;
590       Decl   : Node_Id;
591       Expr   : Node_Id   := Empty;
592       Fun    : Node_Id   := Empty;
593       Is_Dyn : constant Boolean :=
594                  Nkind (Parent (Id_Ref)) = N_Assignment_Statement
595                    and then
596                  Nkind (Expression (Parent (Id_Ref))) = N_Allocator;
597
598    begin
599       --  If Discard_Names or No_Implicit_Heap_Allocations are in effect,
600       --  generate a dummy declaration only.
601
602       if Restriction_Active (No_Implicit_Heap_Allocations)
603         or else Global_Discard_Names
604       then
605          T_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
606          Name_Len := 0;
607
608          return
609            New_List (
610              Make_Object_Declaration (Loc,
611                Defining_Identifier => T_Id,
612                Object_Definition => New_Occurrence_Of (Standard_String, Loc),
613                Expression =>
614                  Make_String_Literal (Loc,
615                    Strval => String_From_Name_Buffer)));
616
617       else
618          if Nkind (Id_Ref) = N_Identifier
619            or else Nkind (Id_Ref) = N_Defining_Identifier
620          then
621             --  For a simple variable, the image of the task is built from
622             --  the name of the variable. To avoid possible conflict with
623             --  the anonymous type created for a single protected object,
624             --  add a numeric suffix.
625
626             T_Id :=
627               Make_Defining_Identifier (Loc,
628                 New_External_Name (Chars (Id_Ref), 'T', 1));
629
630             Get_Name_String (Chars (Id_Ref));
631
632             Expr :=
633               Make_String_Literal (Loc,
634                 Strval => String_From_Name_Buffer);
635
636          elsif Nkind (Id_Ref) = N_Selected_Component then
637             T_Id :=
638               Make_Defining_Identifier (Loc,
639                 New_External_Name (Chars (Selector_Name (Id_Ref)), 'T'));
640             Fun := Build_Task_Record_Image (Loc, Id_Ref, Is_Dyn);
641
642          elsif Nkind (Id_Ref) = N_Indexed_Component then
643             T_Id :=
644               Make_Defining_Identifier (Loc,
645                 New_External_Name (Chars (A_Type), 'N'));
646
647             Fun := Build_Task_Array_Image (Loc, Id_Ref, A_Type, Is_Dyn);
648          end if;
649       end if;
650
651       if Present (Fun) then
652          Append (Fun, Decls);
653          Expr := Make_Function_Call (Loc,
654            Name => New_Occurrence_Of (Defining_Entity (Fun), Loc));
655
656          if not In_Init_Proc then
657             Set_Uses_Sec_Stack (Defining_Entity (Fun));
658          end if;
659       end if;
660
661       Decl := Make_Object_Declaration (Loc,
662         Defining_Identifier => T_Id,
663         Object_Definition   => New_Occurrence_Of (Standard_String, Loc),
664         Constant_Present    => True,
665         Expression          => Expr);
666
667       Append (Decl, Decls);
668       return Decls;
669    end Build_Task_Image_Decls;
670
671    -------------------------------
672    -- Build_Task_Image_Function --
673    -------------------------------
674
675    function Build_Task_Image_Function
676      (Loc   : Source_Ptr;
677       Decls : List_Id;
678       Stats : List_Id;
679       Res   : Entity_Id) return Node_Id
680    is
681       Spec : Node_Id;
682
683    begin
684       Append_To (Stats,
685         Make_Return_Statement (Loc,
686           Expression => New_Occurrence_Of (Res, Loc)));
687
688       Spec := Make_Function_Specification (Loc,
689         Defining_Unit_Name =>
690           Make_Defining_Identifier (Loc, New_Internal_Name ('F')),
691         Result_Definition => New_Occurrence_Of (Standard_String, Loc));
692
693       --  Calls to 'Image use the secondary stack, which must be cleaned
694       --  up after the task name is built.
695
696       return Make_Subprogram_Body (Loc,
697          Specification => Spec,
698          Declarations => Decls,
699          Handled_Statement_Sequence =>
700            Make_Handled_Sequence_Of_Statements (Loc, Statements => Stats));
701    end Build_Task_Image_Function;
702
703    -----------------------------
704    -- Build_Task_Image_Prefix --
705    -----------------------------
706
707    procedure Build_Task_Image_Prefix
708       (Loc    : Source_Ptr;
709        Len    : out Entity_Id;
710        Res    : out Entity_Id;
711        Pos    : out Entity_Id;
712        Prefix : Entity_Id;
713        Sum    : Node_Id;
714        Decls  : in out List_Id;
715        Stats  : in out List_Id)
716    is
717    begin
718       Len := Make_Defining_Identifier (Loc, New_Internal_Name ('L'));
719
720       Append_To (Decls,
721         Make_Object_Declaration (Loc,
722           Defining_Identifier => Len,
723           Object_Definition => New_Occurrence_Of (Standard_Integer, Loc),
724           Expression        => Sum));
725
726       Res := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
727
728       Append_To (Decls,
729          Make_Object_Declaration (Loc,
730             Defining_Identifier => Res,
731             Object_Definition =>
732                Make_Subtype_Indication (Loc,
733                   Subtype_Mark => New_Occurrence_Of (Standard_String, Loc),
734                Constraint =>
735                  Make_Index_Or_Discriminant_Constraint (Loc,
736                    Constraints =>
737                      New_List (
738                        Make_Range (Loc,
739                          Low_Bound => Make_Integer_Literal (Loc, 1),
740                          High_Bound => New_Occurrence_Of (Len, Loc)))))));
741
742       Pos := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
743
744       Append_To (Decls,
745          Make_Object_Declaration (Loc,
746             Defining_Identifier => Pos,
747             Object_Definition => New_Occurrence_Of (Standard_Integer, Loc)));
748
749       --  Pos := Prefix'Length;
750
751       Append_To (Stats,
752          Make_Assignment_Statement (Loc,
753             Name => New_Occurrence_Of (Pos, Loc),
754             Expression =>
755               Make_Attribute_Reference (Loc,
756                 Attribute_Name => Name_Length,
757                 Prefix => New_Occurrence_Of (Prefix, Loc),
758                 Expressions =>
759                     New_List (Make_Integer_Literal (Loc, 1)))));
760
761       --  Res (1 .. Pos) := Prefix;
762
763       Append_To (Stats,
764          Make_Assignment_Statement (Loc,
765            Name => Make_Slice (Loc,
766               Prefix => New_Occurrence_Of (Res, Loc),
767               Discrete_Range  =>
768                 Make_Range (Loc,
769                    Low_Bound => Make_Integer_Literal (Loc, 1),
770                    High_Bound => New_Occurrence_Of (Pos, Loc))),
771
772            Expression => New_Occurrence_Of (Prefix, Loc)));
773
774       Append_To (Stats,
775          Make_Assignment_Statement (Loc,
776             Name => New_Occurrence_Of (Pos, Loc),
777             Expression =>
778               Make_Op_Add (Loc,
779                 Left_Opnd => New_Occurrence_Of (Pos, Loc),
780                 Right_Opnd => Make_Integer_Literal (Loc, 1))));
781    end Build_Task_Image_Prefix;
782
783    -----------------------------
784    -- Build_Task_Record_Image --
785    -----------------------------
786
787    function Build_Task_Record_Image
788      (Loc    : Source_Ptr;
789       Id_Ref : Node_Id;
790       Dyn    : Boolean := False) return Node_Id
791    is
792       Len : Entity_Id;
793       --  Total length of generated name
794
795       Pos : Entity_Id;
796       --  Index into result
797
798       Res : Entity_Id;
799       --  String to hold result
800
801       Pref : Entity_Id;
802       --  Name of enclosing variable, prefix of resulting name
803
804       Sum : Node_Id;
805       --  Expression to compute total size of string
806
807       Sel : Entity_Id;
808       --  Entity for selector name
809
810       Decls : List_Id := New_List;
811       Stats : List_Id := New_List;
812
813    begin
814       Pref := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
815
816       --  For a dynamic task, the name comes from the target variable.
817       --  For a static one it is a formal of the enclosing init proc.
818
819       if Dyn then
820          Get_Name_String (Chars (Entity (Prefix (Id_Ref))));
821          Append_To (Decls,
822            Make_Object_Declaration (Loc,
823              Defining_Identifier => Pref,
824              Object_Definition => New_Occurrence_Of (Standard_String, Loc),
825              Expression =>
826                Make_String_Literal (Loc,
827                  Strval => String_From_Name_Buffer)));
828
829       else
830          Append_To (Decls,
831            Make_Object_Renaming_Declaration (Loc,
832              Defining_Identifier => Pref,
833              Subtype_Mark        => New_Occurrence_Of (Standard_String, Loc),
834              Name                => Make_Identifier (Loc, Name_uTask_Name)));
835       end if;
836
837       Sel := Make_Defining_Identifier (Loc, New_Internal_Name ('S'));
838
839       Get_Name_String (Chars (Selector_Name (Id_Ref)));
840
841       Append_To (Decls,
842          Make_Object_Declaration (Loc,
843            Defining_Identifier => Sel,
844            Object_Definition => New_Occurrence_Of (Standard_String, Loc),
845            Expression =>
846              Make_String_Literal (Loc,
847                Strval => String_From_Name_Buffer)));
848
849       Sum := Make_Integer_Literal (Loc, Nat (Name_Len + 1));
850
851       Sum :=
852         Make_Op_Add (Loc,
853           Left_Opnd => Sum,
854           Right_Opnd =>
855            Make_Attribute_Reference (Loc,
856              Attribute_Name => Name_Length,
857              Prefix =>
858                New_Occurrence_Of (Pref, Loc),
859              Expressions => New_List (Make_Integer_Literal (Loc, 1))));
860
861       Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats);
862
863       Set_Character_Literal_Name (Char_Code (Character'Pos ('.')));
864
865       --  Res (Pos) := '.';
866
867       Append_To (Stats,
868          Make_Assignment_Statement (Loc,
869            Name => Make_Indexed_Component (Loc,
870               Prefix => New_Occurrence_Of (Res, Loc),
871               Expressions => New_List (New_Occurrence_Of (Pos, Loc))),
872            Expression =>
873              Make_Character_Literal (Loc,
874                Chars => Name_Find,
875                Char_Literal_Value =>
876                  UI_From_Int (Character'Pos ('.')))));
877
878       Append_To (Stats,
879         Make_Assignment_Statement (Loc,
880           Name => New_Occurrence_Of (Pos, Loc),
881           Expression =>
882             Make_Op_Add (Loc,
883               Left_Opnd => New_Occurrence_Of (Pos, Loc),
884               Right_Opnd => Make_Integer_Literal (Loc, 1))));
885
886       --  Res (Pos .. Len) := Selector;
887
888       Append_To (Stats,
889         Make_Assignment_Statement (Loc,
890           Name => Make_Slice (Loc,
891              Prefix => New_Occurrence_Of (Res, Loc),
892              Discrete_Range  =>
893                Make_Range (Loc,
894                  Low_Bound  => New_Occurrence_Of (Pos, Loc),
895                  High_Bound => New_Occurrence_Of (Len, Loc))),
896           Expression => New_Occurrence_Of (Sel, Loc)));
897
898       return Build_Task_Image_Function (Loc, Decls, Stats, Res);
899    end Build_Task_Record_Image;
900
901    ----------------------------------
902    -- Component_May_Be_Bit_Aligned --
903    ----------------------------------
904
905    function Component_May_Be_Bit_Aligned (Comp : Entity_Id) return Boolean is
906    begin
907       --  If no component clause, then everything is fine, since the
908       --  back end never bit-misaligns by default, even if there is
909       --  a pragma Packed for the record.
910
911       if No (Component_Clause (Comp)) then
912          return False;
913       end if;
914
915       --  It is only array and record types that cause trouble
916
917       if not Is_Record_Type (Etype (Comp))
918         and then not Is_Array_Type (Etype (Comp))
919       then
920          return False;
921
922       --  If we know that we have a small (64 bits or less) record
923       --  or bit-packed array, then everything is fine, since the
924       --  back end can handle these cases correctly.
925
926       elsif Esize (Comp) <= 64
927         and then (Is_Record_Type (Etype (Comp))
928                    or else Is_Bit_Packed_Array (Etype (Comp)))
929       then
930          return False;
931
932       --  Otherwise if the component is not byte aligned, we
933       --  know we have the nasty unaligned case.
934
935       elsif Normalized_First_Bit (Comp) /= Uint_0
936         or else Esize (Comp) mod System_Storage_Unit /= Uint_0
937       then
938          return True;
939
940       --  If we are large and byte aligned, then OK at this level
941
942       else
943          return False;
944       end if;
945    end Component_May_Be_Bit_Aligned;
946
947    -------------------------------
948    -- Convert_To_Actual_Subtype --
949    -------------------------------
950
951    procedure Convert_To_Actual_Subtype (Exp : Entity_Id) is
952       Act_ST : Entity_Id;
953
954    begin
955       Act_ST := Get_Actual_Subtype (Exp);
956
957       if Act_ST = Etype (Exp) then
958          return;
959
960       else
961          Rewrite (Exp,
962            Convert_To (Act_ST, Relocate_Node (Exp)));
963          Analyze_And_Resolve (Exp, Act_ST);
964       end if;
965    end Convert_To_Actual_Subtype;
966
967    -----------------------------------
968    -- Current_Sem_Unit_Declarations --
969    -----------------------------------
970
971    function Current_Sem_Unit_Declarations return List_Id is
972       U     : Node_Id := Unit (Cunit (Current_Sem_Unit));
973       Decls : List_Id;
974
975    begin
976       --  If the current unit is a package body, locate the visible
977       --  declarations of the package spec.
978
979       if Nkind (U) = N_Package_Body then
980          U := Unit (Library_Unit (Cunit (Current_Sem_Unit)));
981       end if;
982
983       if Nkind (U) = N_Package_Declaration then
984          U := Specification (U);
985          Decls := Visible_Declarations (U);
986
987          if No (Decls) then
988             Decls := New_List;
989             Set_Visible_Declarations (U, Decls);
990          end if;
991
992       else
993          Decls := Declarations (U);
994
995          if No (Decls) then
996             Decls := New_List;
997             Set_Declarations (U, Decls);
998          end if;
999       end if;
1000
1001       return Decls;
1002    end Current_Sem_Unit_Declarations;
1003
1004    -----------------------
1005    -- Duplicate_Subexpr --
1006    -----------------------
1007
1008    function Duplicate_Subexpr
1009      (Exp      : Node_Id;
1010       Name_Req : Boolean := False) return Node_Id
1011    is
1012    begin
1013       Remove_Side_Effects (Exp, Name_Req);
1014       return New_Copy_Tree (Exp);
1015    end Duplicate_Subexpr;
1016
1017    ---------------------------------
1018    -- Duplicate_Subexpr_No_Checks --
1019    ---------------------------------
1020
1021    function Duplicate_Subexpr_No_Checks
1022      (Exp      : Node_Id;
1023       Name_Req : Boolean := False) return Node_Id
1024    is
1025       New_Exp : Node_Id;
1026
1027    begin
1028       Remove_Side_Effects (Exp, Name_Req);
1029       New_Exp := New_Copy_Tree (Exp);
1030       Remove_Checks (New_Exp);
1031       return New_Exp;
1032    end Duplicate_Subexpr_No_Checks;
1033
1034    -----------------------------------
1035    -- Duplicate_Subexpr_Move_Checks --
1036    -----------------------------------
1037
1038    function Duplicate_Subexpr_Move_Checks
1039      (Exp      : Node_Id;
1040       Name_Req : Boolean := False) return Node_Id
1041    is
1042       New_Exp : Node_Id;
1043
1044    begin
1045       Remove_Side_Effects (Exp, Name_Req);
1046       New_Exp := New_Copy_Tree (Exp);
1047       Remove_Checks (Exp);
1048       return New_Exp;
1049    end Duplicate_Subexpr_Move_Checks;
1050
1051    --------------------
1052    -- Ensure_Defined --
1053    --------------------
1054
1055    procedure Ensure_Defined (Typ : Entity_Id; N : Node_Id) is
1056       IR : Node_Id;
1057       P  : Node_Id;
1058
1059    begin
1060       if Is_Itype (Typ) then
1061          IR := Make_Itype_Reference (Sloc (N));
1062          Set_Itype (IR, Typ);
1063
1064          if not In_Open_Scopes (Scope (Typ))
1065            and then Is_Subprogram (Current_Scope)
1066            and then Scope (Current_Scope) /= Standard_Standard
1067          then
1068             --  Insert node in front of subprogram, to avoid scope anomalies
1069             --  in gigi.
1070
1071             P := Parent (N);
1072             while Present (P)
1073               and then Nkind (P) /= N_Subprogram_Body
1074             loop
1075                P := Parent (P);
1076             end loop;
1077
1078             if Present (P) then
1079                Insert_Action (P, IR);
1080             else
1081                Insert_Action (N, IR);
1082             end if;
1083
1084          else
1085             Insert_Action (N, IR);
1086          end if;
1087       end if;
1088    end Ensure_Defined;
1089
1090    ---------------------
1091    -- Evolve_And_Then --
1092    ---------------------
1093
1094    procedure Evolve_And_Then (Cond : in out Node_Id; Cond1 : Node_Id) is
1095    begin
1096       if No (Cond) then
1097          Cond := Cond1;
1098       else
1099          Cond :=
1100            Make_And_Then (Sloc (Cond1),
1101              Left_Opnd  => Cond,
1102              Right_Opnd => Cond1);
1103       end if;
1104    end Evolve_And_Then;
1105
1106    --------------------
1107    -- Evolve_Or_Else --
1108    --------------------
1109
1110    procedure Evolve_Or_Else (Cond : in out Node_Id; Cond1 : Node_Id) is
1111    begin
1112       if No (Cond) then
1113          Cond := Cond1;
1114       else
1115          Cond :=
1116            Make_Or_Else (Sloc (Cond1),
1117              Left_Opnd  => Cond,
1118              Right_Opnd => Cond1);
1119       end if;
1120    end Evolve_Or_Else;
1121
1122    ------------------------------
1123    -- Expand_Subtype_From_Expr --
1124    ------------------------------
1125
1126    --  This function is applicable for both static and dynamic allocation of
1127    --  objects which are constrained by an initial expression. Basically it
1128    --  transforms an unconstrained subtype indication into a constrained one.
1129    --  The expression may also be transformed in certain cases in order to
1130    --  avoid multiple evaluation. In the static allocation case, the general
1131    --  scheme is:
1132
1133    --     Val : T := Expr;
1134
1135    --        is transformed into
1136
1137    --     Val : Constrained_Subtype_of_T := Maybe_Modified_Expr;
1138    --
1139    --  Here are the main cases :
1140    --
1141    --  <if Expr is a Slice>
1142    --    Val : T ([Index_Subtype (Expr)]) := Expr;
1143    --
1144    --  <elsif Expr is a String Literal>
1145    --    Val : T (T'First .. T'First + Length (string literal) - 1) := Expr;
1146    --
1147    --  <elsif Expr is Constrained>
1148    --    subtype T is Type_Of_Expr
1149    --    Val : T := Expr;
1150    --
1151    --  <elsif Expr is an entity_name>
1152    --    Val : T (constraints taken from Expr) := Expr;
1153    --
1154    --  <else>
1155    --    type Axxx is access all T;
1156    --    Rval : Axxx := Expr'ref;
1157    --    Val  : T (constraints taken from Rval) := Rval.all;
1158
1159    --    ??? note: when the Expression is allocated in the secondary stack
1160    --              we could use it directly instead of copying it by declaring
1161    --              Val : T (...) renames Rval.all
1162
1163    procedure Expand_Subtype_From_Expr
1164      (N             : Node_Id;
1165       Unc_Type      : Entity_Id;
1166       Subtype_Indic : Node_Id;
1167       Exp           : Node_Id)
1168    is
1169       Loc     : constant Source_Ptr := Sloc (N);
1170       Exp_Typ : constant Entity_Id  := Etype (Exp);
1171       T       : Entity_Id;
1172
1173    begin
1174       --  In general we cannot build the subtype if expansion is disabled,
1175       --  because internal entities may not have been defined. However, to
1176       --  avoid some cascaded errors, we try to continue when the expression
1177       --  is an array (or string), because it is safe to compute the bounds.
1178       --  It is in fact required to do so even in a generic context, because
1179       --  there may be constants that depend on bounds of string literal.
1180
1181       if not Expander_Active
1182         and then (No (Etype (Exp))
1183                    or else Base_Type (Etype (Exp)) /= Standard_String)
1184       then
1185          return;
1186       end if;
1187
1188       if Nkind (Exp) = N_Slice then
1189          declare
1190             Slice_Type : constant Entity_Id := Etype (First_Index (Exp_Typ));
1191
1192          begin
1193             Rewrite (Subtype_Indic,
1194               Make_Subtype_Indication (Loc,
1195                 Subtype_Mark => New_Reference_To (Unc_Type, Loc),
1196                 Constraint =>
1197                   Make_Index_Or_Discriminant_Constraint (Loc,
1198                     Constraints => New_List
1199                       (New_Reference_To (Slice_Type, Loc)))));
1200
1201             --  This subtype indication may be used later for contraint checks
1202             --  we better make sure that if a variable was used as a bound of
1203             --  of the original slice, its value is frozen.
1204
1205             Force_Evaluation (Low_Bound (Scalar_Range (Slice_Type)));
1206             Force_Evaluation (High_Bound (Scalar_Range (Slice_Type)));
1207          end;
1208
1209       elsif Ekind (Exp_Typ) = E_String_Literal_Subtype then
1210          Rewrite (Subtype_Indic,
1211            Make_Subtype_Indication (Loc,
1212              Subtype_Mark => New_Reference_To (Unc_Type, Loc),
1213              Constraint =>
1214                Make_Index_Or_Discriminant_Constraint (Loc,
1215                  Constraints => New_List (
1216                    Make_Literal_Range (Loc,
1217                      Literal_Typ => Exp_Typ)))));
1218
1219       elsif Is_Constrained (Exp_Typ)
1220         and then not Is_Class_Wide_Type (Unc_Type)
1221       then
1222          if Is_Itype (Exp_Typ) then
1223
1224             --  Within an initialization procedure, a selected component
1225             --  denotes a component of the enclosing record, and it appears
1226             --  as an actual in a call to its own initialization procedure.
1227             --  If this component depends on the outer discriminant, we must
1228             --  generate the proper actual subtype for it.
1229
1230             if Nkind (Exp) = N_Selected_Component
1231               and then Within_Init_Proc
1232             then
1233                declare
1234                   Decl : constant Node_Id :=
1235                            Build_Actual_Subtype_Of_Component (Exp_Typ, Exp);
1236                begin
1237                   if Present (Decl) then
1238                      Insert_Action (N, Decl);
1239                      T := Defining_Identifier (Decl);
1240                   else
1241                      T := Exp_Typ;
1242                   end if;
1243                end;
1244
1245             --  No need to generate a new one (new what???)
1246
1247             else
1248                T := Exp_Typ;
1249             end if;
1250
1251          else
1252             T :=
1253               Make_Defining_Identifier (Loc,
1254                 Chars => New_Internal_Name ('T'));
1255
1256             Insert_Action (N,
1257               Make_Subtype_Declaration (Loc,
1258                 Defining_Identifier => T,
1259                 Subtype_Indication  => New_Reference_To (Exp_Typ, Loc)));
1260
1261             --  This type is marked as an itype even though it has an
1262             --  explicit declaration because otherwise it can be marked
1263             --  with Is_Generic_Actual_Type and generate spurious errors.
1264             --  (see sem_ch8.Analyze_Package_Renaming and sem_type.covers)
1265
1266             Set_Is_Itype (T);
1267             Set_Associated_Node_For_Itype (T, Exp);
1268          end if;
1269
1270          Rewrite (Subtype_Indic, New_Reference_To (T, Loc));
1271
1272       --  nothing needs to be done for private types with unknown discriminants
1273       --  if the underlying type is not an unconstrained composite type.
1274
1275       elsif Is_Private_Type (Unc_Type)
1276         and then Has_Unknown_Discriminants (Unc_Type)
1277         and then (not Is_Composite_Type (Underlying_Type (Unc_Type))
1278                     or else Is_Constrained (Underlying_Type (Unc_Type)))
1279       then
1280          null;
1281
1282       --  Nothing to be done for derived types with unknown discriminants if
1283       --  the parent type also has unknown discriminants.
1284
1285       elsif Is_Record_Type (Unc_Type)
1286         and then not Is_Class_Wide_Type (Unc_Type)
1287         and then Has_Unknown_Discriminants (Unc_Type)
1288         and then Has_Unknown_Discriminants (Underlying_Type (Unc_Type))
1289       then
1290          null;
1291
1292       --  Nothing to be done if the type of the expression is limited, because
1293       --  in this case the expression cannot be copied, and its use can only
1294       --  be by reference and there is no need for the actual subtype.
1295
1296       elsif Is_Limited_Type (Exp_Typ) then
1297          null;
1298
1299       else
1300          Remove_Side_Effects (Exp);
1301          Rewrite (Subtype_Indic,
1302            Make_Subtype_From_Expr (Exp, Unc_Type));
1303       end if;
1304    end Expand_Subtype_From_Expr;
1305
1306    --------------------------------
1307    -- Find_Implemented_Interface --
1308    --------------------------------
1309
1310    --  Given the following code (XXX denotes irrelevant value):
1311
1312    --     type Limd_Iface is limited interface;
1313    --     type Prot_Iface is protected interface;
1314    --     type Sync_Iface is synchronized interface;
1315
1316    --     type Parent_Subtype is new Limd_Iface and Sync_Iface with ...
1317    --     type Child_Subtype is new Parent_Subtype and Prot_Iface with ...
1318
1319    --  The following calls will return the following values:
1320
1321    --     Find_Implemented_Interface
1322    --       (Child_Subtype, Synchronized_Interface, False)    -> Empty
1323
1324    --     Find_Implemented_Interface
1325    --       (Child_Subtype, Synchronized_Interface, True)     -> Sync_Iface
1326
1327    --     Find_Implemented_Interface
1328    --       (Child_Subtype, Any_Synchronized_Interface, XXX)  -> Prot_Iface
1329
1330    --     Find_Implemented_Interface
1331    --       (Child_Subtype, Any_Limited_Interface, XXX)       -> Prot_Iface
1332
1333    function Find_Implemented_Interface
1334      (Typ          : Entity_Id;
1335       Kind         : Interface_Kind;
1336       Check_Parent : Boolean := False) return Entity_Id
1337    is
1338       Iface_Elmt : Elmt_Id;
1339
1340       function Interface_In_Kind
1341         (I    : Entity_Id;
1342          Kind : Interface_Kind) return Boolean;
1343       --  Determine whether an interface falls into a specified kind
1344
1345       -----------------------
1346       -- Interface_In_Kind --
1347       -----------------------
1348
1349       function Interface_In_Kind
1350         (I    : Entity_Id;
1351          Kind : Interface_Kind) return Boolean is
1352       begin
1353          if Is_Limited_Interface (I)
1354            and then (Kind = Any_Interface
1355              or else Kind = Any_Limited_Interface
1356              or else Kind = Limited_Interface)
1357          then
1358             return True;
1359
1360          elsif Is_Protected_Interface (I)
1361            and then (Kind = Any_Interface
1362              or else Kind = Any_Limited_Interface
1363              or else Kind = Any_Synchronized_Interface
1364              or else Kind = Protected_Interface)
1365          then
1366             return True;
1367
1368          elsif Is_Synchronized_Interface (I)
1369            and then (Kind = Any_Interface
1370              or else Kind = Any_Limited_Interface
1371              or else Kind = Synchronized_Interface)
1372          then
1373             return True;
1374
1375          elsif Is_Task_Interface (I)
1376            and then (Kind = Any_Interface
1377              or else Kind = Any_Limited_Interface
1378              or else Kind = Any_Synchronized_Interface
1379              or else Kind = Task_Interface)
1380          then
1381             return True;
1382
1383          --  Regular interface. This should be the last kind to check since
1384          --  all of the previous cases have their Is_Interface flags set.
1385
1386          elsif Is_Interface (I)
1387            and then (Kind = Any_Interface
1388              or else Kind = Iface)
1389          then
1390             return True;
1391
1392          else
1393             return False;
1394          end if;
1395       end Interface_In_Kind;
1396
1397    --  Start of processing for Find_Implemented_Interface
1398
1399    begin
1400       if not Is_Tagged_Type (Typ) then
1401          return Empty;
1402       end if;
1403
1404       --  Implementations of the form:
1405       --    Typ is new Interface ...
1406
1407       if Is_Interface (Etype (Typ))
1408         and then Interface_In_Kind (Etype (Typ), Kind)
1409       then
1410          return Etype (Typ);
1411       end if;
1412
1413       --  Implementations of the form:
1414       --     Typ is new Typ_Parent and Interface ...
1415
1416       if Present (Abstract_Interfaces (Typ)) then
1417          Iface_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1418          while Present (Iface_Elmt) loop
1419             if Interface_In_Kind (Node (Iface_Elmt), Kind) then
1420                return Node (Iface_Elmt);
1421             end if;
1422
1423             Iface_Elmt := Next_Elmt (Iface_Elmt);
1424          end loop;
1425       end if;
1426
1427       --  Typ is a derived type and may implement a limited interface
1428       --  through its parent subtype. Check the parent subtype as well
1429       --  as any interfaces explicitly implemented at this level.
1430
1431       if Check_Parent
1432         and then Ekind (Typ) = E_Record_Type
1433         and then Present (Parent_Subtype (Typ))
1434       then
1435          return Find_Implemented_Interface (
1436            Parent_Subtype (Typ), Kind, Check_Parent);
1437       end if;
1438
1439       --  Typ does not implement a limited interface either at this level or
1440       --  in any of its parent subtypes.
1441
1442       return Empty;
1443    end Find_Implemented_Interface;
1444
1445    ------------------------
1446    -- Find_Interface_ADT --
1447    ------------------------
1448
1449    function Find_Interface_ADT
1450      (T     : Entity_Id;
1451       Iface : Entity_Id) return Entity_Id
1452    is
1453       ADT   : Elmt_Id;
1454       Found : Boolean   := False;
1455       Typ   : Entity_Id := T;
1456
1457       procedure Find_Secondary_Table (Typ : Entity_Id);
1458       --  Internal subprogram used to recursively climb to the ancestors
1459
1460       --------------------------
1461       -- Find_Secondary_Table --
1462       --------------------------
1463
1464       procedure Find_Secondary_Table (Typ : Entity_Id) is
1465          AI_Elmt : Elmt_Id;
1466          AI      : Node_Id;
1467
1468       begin
1469          --  Climb to the ancestor (if any) handling private types
1470
1471          if Present (Full_View (Etype (Typ))) then
1472             if Full_View (Etype (Typ)) /= Typ then
1473                Find_Secondary_Table (Full_View (Etype (Typ)));
1474             end if;
1475
1476          elsif Etype (Typ) /= Typ then
1477             Find_Secondary_Table (Etype (Typ));
1478          end if;
1479
1480          --  If we already found it there is nothing else to do
1481
1482          if Found then
1483             return;
1484          end if;
1485
1486          if Present (Abstract_Interfaces (Typ))
1487            and then not Is_Empty_Elmt_List (Abstract_Interfaces (Typ))
1488          then
1489             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1490             while Present (AI_Elmt) loop
1491                AI := Node (AI_Elmt);
1492
1493                if AI = Iface or else Is_Ancestor (Iface, AI) then
1494                   Found := True;
1495                   return;
1496                end if;
1497
1498                Next_Elmt (ADT);
1499                Next_Elmt (AI_Elmt);
1500             end loop;
1501          end if;
1502       end Find_Secondary_Table;
1503
1504    --  Start of processing for Find_Interface_Tag
1505
1506    begin
1507       --  Handle private types
1508
1509       if Has_Private_Declaration (Typ)
1510         and then Present (Full_View (Typ))
1511       then
1512          Typ := Full_View (Typ);
1513       end if;
1514
1515       --  Handle access types
1516
1517       if Is_Access_Type (Typ) then
1518          Typ := Directly_Designated_Type (Typ);
1519       end if;
1520
1521       --  Handle task and protected types implementing interfaces
1522
1523       if Ekind (Typ) = E_Protected_Type
1524         or else Ekind (Typ) = E_Task_Type
1525       then
1526          Typ := Corresponding_Record_Type (Typ);
1527       end if;
1528
1529       ADT := Next_Elmt (First_Elmt (Access_Disp_Table (Typ)));
1530       pragma Assert (Present (Node (ADT)));
1531       Find_Secondary_Table (Typ);
1532       pragma Assert (Found);
1533       return Node (ADT);
1534    end Find_Interface_ADT;
1535
1536    ------------------------
1537    -- Find_Interface_Tag --
1538    ------------------------
1539
1540    function Find_Interface_Tag
1541      (T      : Entity_Id;
1542       Iface  : Entity_Id) return Entity_Id
1543    is
1544       AI_Tag : Entity_Id;
1545       Found  : Boolean := False;
1546       Typ    : Entity_Id := T;
1547
1548       procedure Find_Tag (Typ : Entity_Id);
1549       --  Internal subprogram used to recursively climb to the ancestors
1550
1551       --------------
1552       -- Find_Tag --
1553       --------------
1554
1555       procedure Find_Tag (Typ : Entity_Id) is
1556          AI_Elmt : Elmt_Id;
1557          AI      : Node_Id;
1558
1559       begin
1560          --  Check if the interface is an immediate ancestor of the type and
1561          --  therefore shares the main tag.
1562
1563          if Typ = Iface then
1564             pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1565             AI_Tag := First_Tag_Component (Typ);
1566             Found  := True;
1567             return;
1568          end if;
1569
1570          --  Climb to the root type handling private types
1571
1572          if Present (Full_View (Etype (Typ))) then
1573             if Full_View (Etype (Typ)) /= Typ then
1574                Find_Tag (Full_View (Etype (Typ)));
1575             end if;
1576
1577          elsif Etype (Typ) /= Typ then
1578             Find_Tag (Etype (Typ));
1579          end if;
1580
1581          --  Traverse the list of interfaces implemented by the type
1582
1583          if not Found
1584            and then Present (Abstract_Interfaces (Typ))
1585            and then not (Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1586          then
1587             --  Skip the tag associated with the primary table
1588
1589             pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1590             AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1591             pragma Assert (Present (AI_Tag));
1592
1593             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1594             while Present (AI_Elmt) loop
1595                AI := Node (AI_Elmt);
1596
1597                if AI = Iface or else Is_Ancestor (Iface, AI) then
1598                   Found := True;
1599                   return;
1600                end if;
1601
1602                AI_Tag := Next_Tag_Component (AI_Tag);
1603                Next_Elmt (AI_Elmt);
1604             end loop;
1605          end if;
1606       end Find_Tag;
1607
1608    --  Start of processing for Find_Interface_Tag
1609
1610    begin
1611       pragma Assert (Is_Interface (Iface));
1612
1613       --  Handle private types
1614
1615       if Has_Private_Declaration (Typ)
1616         and then Present (Full_View (Typ))
1617       then
1618          Typ := Full_View (Typ);
1619       end if;
1620
1621       --  Handle access types
1622
1623       if Is_Access_Type (Typ) then
1624          Typ := Directly_Designated_Type (Typ);
1625       end if;
1626
1627       --  Handle task and protected types implementing interfaces
1628
1629       if Is_Concurrent_Type (Typ) then
1630          Typ := Corresponding_Record_Type (Typ);
1631       end if;
1632
1633       if Is_Class_Wide_Type (Typ) then
1634          Typ := Etype (Typ);
1635       end if;
1636
1637       --  Handle entities from the limited view
1638
1639       if Ekind (Typ) = E_Incomplete_Type then
1640          pragma Assert (Present (Non_Limited_View (Typ)));
1641          Typ := Non_Limited_View (Typ);
1642       end if;
1643
1644       Find_Tag (Typ);
1645       pragma Assert (Found);
1646       return AI_Tag;
1647    end Find_Interface_Tag;
1648
1649    --------------------
1650    -- Find_Interface --
1651    --------------------
1652
1653    function Find_Interface
1654      (T      : Entity_Id;
1655       Comp   : Entity_Id) return Entity_Id
1656    is
1657       AI_Tag : Entity_Id;
1658       Found  : Boolean := False;
1659       Iface  : Entity_Id;
1660       Typ    : Entity_Id := T;
1661
1662       procedure Find_Iface (Typ : Entity_Id);
1663       --  Internal subprogram used to recursively climb to the ancestors
1664
1665       ----------------
1666       -- Find_Iface --
1667       ----------------
1668
1669       procedure Find_Iface (Typ : Entity_Id) is
1670          AI_Elmt : Elmt_Id;
1671
1672       begin
1673          --  Climb to the root type
1674
1675          if Etype (Typ) /= Typ then
1676             Find_Iface (Etype (Typ));
1677          end if;
1678
1679          --  Traverse the list of interfaces implemented by the type
1680
1681          if not Found
1682            and then Present (Abstract_Interfaces (Typ))
1683            and then not (Is_Empty_Elmt_List (Abstract_Interfaces (Typ)))
1684          then
1685             --  Skip the tag associated with the primary table
1686
1687             pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag));
1688             AI_Tag := Next_Tag_Component (First_Tag_Component (Typ));
1689             pragma Assert (Present (AI_Tag));
1690
1691             AI_Elmt := First_Elmt (Abstract_Interfaces (Typ));
1692             while Present (AI_Elmt) loop
1693                if AI_Tag = Comp then
1694                   Iface := Node (AI_Elmt);
1695                   Found := True;
1696                   return;
1697                end if;
1698
1699                AI_Tag := Next_Tag_Component (AI_Tag);
1700                Next_Elmt (AI_Elmt);
1701             end loop;
1702          end if;
1703       end Find_Iface;
1704
1705    --  Start of processing for Find_Interface
1706
1707    begin
1708       --  Handle private types
1709
1710       if Has_Private_Declaration (Typ)
1711         and then Present (Full_View (Typ))
1712       then
1713          Typ := Full_View (Typ);
1714       end if;
1715
1716       --  Handle access types
1717
1718       if Is_Access_Type (Typ) then
1719          Typ := Directly_Designated_Type (Typ);
1720       end if;
1721
1722       --  Handle task and protected types implementing interfaces
1723
1724       if Is_Concurrent_Type (Typ) then
1725          Typ := Corresponding_Record_Type (Typ);
1726       end if;
1727
1728       if Is_Class_Wide_Type (Typ) then
1729          Typ := Etype (Typ);
1730       end if;
1731
1732       --  Handle entities from the limited view
1733
1734       if Ekind (Typ) = E_Incomplete_Type then
1735          pragma Assert (Present (Non_Limited_View (Typ)));
1736          Typ := Non_Limited_View (Typ);
1737       end if;
1738
1739       Find_Iface (Typ);
1740       pragma Assert (Found);
1741       return Iface;
1742    end Find_Interface;
1743
1744    ------------------
1745    -- Find_Prim_Op --
1746    ------------------
1747
1748    function Find_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id is
1749       Prim : Elmt_Id;
1750       Typ  : Entity_Id := T;
1751       Op   : Entity_Id;
1752
1753    begin
1754       if Is_Class_Wide_Type (Typ) then
1755          Typ := Root_Type (Typ);
1756       end if;
1757
1758       Typ := Underlying_Type (Typ);
1759
1760       --  Loop through primitive operations
1761
1762       Prim := First_Elmt (Primitive_Operations (Typ));
1763       while Present (Prim) loop
1764          Op := Node (Prim);
1765
1766          --  We can retrieve primitive operations by name if it is an internal
1767          --  name. For equality we must check that both of its operands have
1768          --  the same type, to avoid confusion with user-defined equalities
1769          --  than may have a non-symmetric signature.
1770
1771          exit when Chars (Op) = Name
1772            and then
1773              (Name /= Name_Op_Eq
1774                 or else Etype (First_Entity (Op)) = Etype (Last_Entity (Op)));
1775
1776          Next_Elmt (Prim);
1777          pragma Assert (Present (Prim));
1778       end loop;
1779
1780       return Node (Prim);
1781    end Find_Prim_Op;
1782
1783    function Find_Prim_Op
1784      (T    : Entity_Id;
1785       Name : TSS_Name_Type) return Entity_Id
1786    is
1787       Prim : Elmt_Id;
1788       Typ  : Entity_Id := T;
1789
1790    begin
1791       if Is_Class_Wide_Type (Typ) then
1792          Typ := Root_Type (Typ);
1793       end if;
1794
1795       Typ := Underlying_Type (Typ);
1796
1797       Prim := First_Elmt (Primitive_Operations (Typ));
1798       while not Is_TSS (Node (Prim), Name) loop
1799          Next_Elmt (Prim);
1800          pragma Assert (Present (Prim));
1801       end loop;
1802
1803       return Node (Prim);
1804    end Find_Prim_Op;
1805
1806    ----------------------
1807    -- Force_Evaluation --
1808    ----------------------
1809
1810    procedure Force_Evaluation (Exp : Node_Id; Name_Req : Boolean := False) is
1811    begin
1812       Remove_Side_Effects (Exp, Name_Req, Variable_Ref => True);
1813    end Force_Evaluation;
1814
1815    ------------------------
1816    -- Generate_Poll_Call --
1817    ------------------------
1818
1819    procedure Generate_Poll_Call (N : Node_Id) is
1820    begin
1821       --  No poll call if polling not active
1822
1823       if not Polling_Required then
1824          return;
1825
1826       --  Otherwise generate require poll call
1827
1828       else
1829          Insert_Before_And_Analyze (N,
1830            Make_Procedure_Call_Statement (Sloc (N),
1831              Name => New_Occurrence_Of (RTE (RE_Poll), Sloc (N))));
1832       end if;
1833    end Generate_Poll_Call;
1834
1835    ---------------------------------
1836    -- Get_Current_Value_Condition --
1837    ---------------------------------
1838
1839    --  Note: the implementation of this procedure is very closely tied to the
1840    --  implementation of Set_Current_Value_Condition. In the Get procedure, we
1841    --  interpret Current_Value fields set by the Set procedure, so the two
1842    --  procedures need to be closely coordinated.
1843
1844    procedure Get_Current_Value_Condition
1845      (Var : Node_Id;
1846       Op  : out Node_Kind;
1847       Val : out Node_Id)
1848    is
1849       Loc : constant Source_Ptr := Sloc (Var);
1850       Ent : constant Entity_Id  := Entity (Var);
1851
1852       procedure Process_Current_Value_Condition
1853         (N : Node_Id;
1854          S : Boolean);
1855       --  N is an expression which holds either True (S = True) or False (S =
1856       --  False) in the condition. This procedure digs out the expression and
1857       --  if it refers to Ent, sets Op and Val appropriately.
1858
1859       -------------------------------------
1860       -- Process_Current_Value_Condition --
1861       -------------------------------------
1862
1863       procedure Process_Current_Value_Condition
1864         (N : Node_Id;
1865          S : Boolean)
1866       is
1867          Cond : Node_Id;
1868          Sens : Boolean;
1869
1870       begin
1871          Cond := N;
1872          Sens := S;
1873
1874          --  Deal with NOT operators, inverting sense
1875
1876          while Nkind (Cond) = N_Op_Not loop
1877             Cond := Right_Opnd (Cond);
1878             Sens := not Sens;
1879          end loop;
1880
1881          --  Deal with AND THEN and AND cases
1882
1883          if Nkind (Cond) = N_And_Then
1884            or else Nkind (Cond) = N_Op_And
1885          then
1886             --  Don't ever try to invert a condition that is of the form
1887             --  of an AND or AND THEN (since we are not doing sufficiently
1888             --  general processing to allow this).
1889
1890             if Sens = False then
1891                Op  := N_Empty;
1892                Val := Empty;
1893                return;
1894             end if;
1895
1896             --  Recursively process AND and AND THEN branches
1897
1898             Process_Current_Value_Condition (Left_Opnd (Cond), True);
1899
1900             if Op /= N_Empty then
1901                return;
1902             end if;
1903
1904             Process_Current_Value_Condition (Right_Opnd (Cond), True);
1905             return;
1906
1907          --  Case of relational operator
1908
1909          elsif Nkind (Cond) in N_Op_Compare then
1910             Op := Nkind (Cond);
1911
1912             --  Invert sense of test if inverted test
1913
1914             if Sens = False then
1915                case Op is
1916                   when N_Op_Eq => Op := N_Op_Ne;
1917                   when N_Op_Ne => Op := N_Op_Eq;
1918                   when N_Op_Lt => Op := N_Op_Ge;
1919                   when N_Op_Gt => Op := N_Op_Le;
1920                   when N_Op_Le => Op := N_Op_Gt;
1921                   when N_Op_Ge => Op := N_Op_Lt;
1922                   when others  => raise Program_Error;
1923                end case;
1924             end if;
1925
1926             --  Case of entity op value
1927
1928             if Is_Entity_Name (Left_Opnd (Cond))
1929               and then Ent = Entity (Left_Opnd (Cond))
1930               and then Compile_Time_Known_Value (Right_Opnd (Cond))
1931             then
1932                Val := Right_Opnd (Cond);
1933
1934             --  Case of value op entity
1935
1936             elsif Is_Entity_Name (Right_Opnd (Cond))
1937               and then Ent = Entity (Right_Opnd (Cond))
1938               and then Compile_Time_Known_Value (Left_Opnd (Cond))
1939             then
1940                Val := Left_Opnd (Cond);
1941
1942                --  We are effectively swapping operands
1943
1944                case Op is
1945                   when N_Op_Eq => null;
1946                   when N_Op_Ne => null;
1947                   when N_Op_Lt => Op := N_Op_Gt;
1948                   when N_Op_Gt => Op := N_Op_Lt;
1949                   when N_Op_Le => Op := N_Op_Ge;
1950                   when N_Op_Ge => Op := N_Op_Le;
1951                   when others  => raise Program_Error;
1952                end case;
1953
1954             else
1955                Op := N_Empty;
1956             end if;
1957
1958             return;
1959
1960             --  Case of Boolean variable reference, return as though the
1961             --  reference had said var = True.
1962
1963          else
1964             if Is_Entity_Name (Cond)
1965               and then Ent = Entity (Cond)
1966             then
1967                Val := New_Occurrence_Of (Standard_True, Sloc (Cond));
1968
1969                if Sens = False then
1970                   Op := N_Op_Ne;
1971                else
1972                   Op := N_Op_Eq;
1973                end if;
1974             end if;
1975          end if;
1976       end Process_Current_Value_Condition;
1977
1978    --  Start of processing for Get_Current_Value_Condition
1979
1980    begin
1981       Op  := N_Empty;
1982       Val := Empty;
1983
1984       --  Immediate return, nothing doing, if this is not an object
1985
1986       if Ekind (Ent) not in Object_Kind then
1987          return;
1988       end if;
1989
1990       --  Otherwise examine current value
1991
1992       declare
1993          CV   : constant Node_Id := Current_Value (Ent);
1994          Sens : Boolean;
1995          Stm  : Node_Id;
1996
1997       begin
1998          --  If statement. Condition is known true in THEN section, known False
1999          --  in any ELSIF or ELSE part, and unknown outside the IF statement.
2000
2001          if Nkind (CV) = N_If_Statement then
2002
2003             --  Before start of IF statement
2004
2005             if Loc < Sloc (CV) then
2006                return;
2007
2008                --  After end of IF statement
2009
2010             elsif Loc >= Sloc (CV) + Text_Ptr (UI_To_Int (End_Span (CV))) then
2011                return;
2012             end if;
2013
2014             --  At this stage we know that we are within the IF statement, but
2015             --  unfortunately, the tree does not record the SLOC of the ELSE so
2016             --  we cannot use a simple SLOC comparison to distinguish between
2017             --  the then/else statements, so we have to climb the tree.
2018
2019             declare
2020                N : Node_Id;
2021
2022             begin
2023                N := Parent (Var);
2024                while Parent (N) /= CV loop
2025                   N := Parent (N);
2026
2027                   --  If we fall off the top of the tree, then that's odd, but
2028                   --  perhaps it could occur in some error situation, and the
2029                   --  safest response is simply to assume that the outcome of
2030                   --  the condition is unknown. No point in bombing during an
2031                   --  attempt to optimize things.
2032
2033                   if No (N) then
2034                      return;
2035                   end if;
2036                end loop;
2037
2038                --  Now we have N pointing to a node whose parent is the IF
2039                --  statement in question, so now we can tell if we are within
2040                --  the THEN statements.
2041
2042                if Is_List_Member (N)
2043                  and then List_Containing (N) = Then_Statements (CV)
2044                then
2045                   Sens := True;
2046
2047                --  If the variable reference does not come from source, we
2048                --  cannot reliably tell whether it appears in the else part.
2049                --  In particular, if if appears in generated code for a node
2050                --  that requires finalization, it may be attached to a list
2051                --  that has not been yet inserted into the code. For now,
2052                --  treat it as unknown.
2053
2054                elsif not Comes_From_Source (N) then
2055                   return;
2056
2057                --  Otherwise we must be in ELSIF or ELSE part
2058
2059                else
2060                   Sens := False;
2061                end if;
2062             end;
2063
2064             --  ELSIF part. Condition is known true within the referenced
2065             --  ELSIF, known False in any subsequent ELSIF or ELSE part, and
2066             --  unknown before the ELSE part or after the IF statement.
2067
2068          elsif Nkind (CV) = N_Elsif_Part then
2069             Stm := Parent (CV);
2070
2071             --  Before start of ELSIF part
2072
2073             if Loc < Sloc (CV) then
2074                return;
2075
2076                --  After end of IF statement
2077
2078             elsif Loc >= Sloc (Stm) +
2079               Text_Ptr (UI_To_Int (End_Span (Stm)))
2080             then
2081                return;
2082             end if;
2083
2084             --  Again we lack the SLOC of the ELSE, so we need to climb the
2085             --  tree to see if we are within the ELSIF part in question.
2086
2087             declare
2088                N : Node_Id;
2089
2090             begin
2091                N := Parent (Var);
2092                while Parent (N) /= Stm loop
2093                   N := Parent (N);
2094
2095                   --  If we fall off the top of the tree, then that's odd, but
2096                   --  perhaps it could occur in some error situation, and the
2097                   --  safest response is simply to assume that the outcome of
2098                   --  the condition is unknown. No point in bombing during an
2099                   --  attempt to optimize things.
2100
2101                   if No (N) then
2102                      return;
2103                   end if;
2104                end loop;
2105
2106                --  Now we have N pointing to a node whose parent is the IF
2107                --  statement in question, so see if is the ELSIF part we want.
2108                --  the THEN statements.
2109
2110                if N = CV then
2111                   Sens := True;
2112
2113                   --  Otherwise we must be in susbequent ELSIF or ELSE part
2114
2115                else
2116                   Sens := False;
2117                end if;
2118             end;
2119
2120          --  Iteration scheme of while loop. The condition is known to be
2121          --  true within the body of the loop.
2122
2123          elsif Nkind (CV) = N_Iteration_Scheme then
2124             declare
2125                Loop_Stmt : constant Node_Id := Parent (CV);
2126
2127             begin
2128                --  Before start of body of loop
2129
2130                if Loc < Sloc (Loop_Stmt) then
2131                   return;
2132
2133                --  After end of LOOP statement
2134
2135                elsif Loc >= Sloc (End_Label (Loop_Stmt)) then
2136                   return;
2137
2138                --  We are within the body of the loop
2139
2140                else
2141                   Sens := True;
2142                end if;
2143             end;
2144
2145          --  All other cases of Current_Value settings
2146
2147          else
2148             return;
2149          end if;
2150
2151          --  If we fall through here, then we have a reportable condition, Sens
2152          --  is True if the condition is true and False if it needs inverting.
2153
2154          Process_Current_Value_Condition (Condition (CV), Sens);
2155       end;
2156    end Get_Current_Value_Condition;
2157
2158    --------------------
2159    -- Homonym_Number --
2160    --------------------
2161
2162    function Homonym_Number (Subp : Entity_Id) return Nat is
2163       Count : Nat;
2164       Hom   : Entity_Id;
2165
2166    begin
2167       Count := 1;
2168       Hom := Homonym (Subp);
2169       while Present (Hom) loop
2170          if Scope (Hom) = Scope (Subp) then
2171             Count := Count + 1;
2172          end if;
2173
2174          Hom := Homonym (Hom);
2175       end loop;
2176
2177       return Count;
2178    end Homonym_Number;
2179
2180    --------------------------
2181    -- Implements_Interface --
2182    --------------------------
2183
2184    function Implements_Interface
2185      (Typ          : Entity_Id;
2186       Kind         : Interface_Kind;
2187       Check_Parent : Boolean := False) return Boolean is
2188    begin
2189       return Find_Implemented_Interface (Typ, Kind, Check_Parent) /= Empty;
2190    end Implements_Interface;
2191
2192    ------------------------------
2193    -- In_Unconditional_Context --
2194    ------------------------------
2195
2196    function In_Unconditional_Context (Node : Node_Id) return Boolean is
2197       P : Node_Id;
2198
2199    begin
2200       P := Node;
2201       while Present (P) loop
2202          case Nkind (P) is
2203             when N_Subprogram_Body =>
2204                return True;
2205
2206             when N_If_Statement =>
2207                return False;
2208
2209             when N_Loop_Statement =>
2210                return False;
2211
2212             when N_Case_Statement =>
2213                return False;
2214
2215             when others =>
2216                P := Parent (P);
2217          end case;
2218       end loop;
2219
2220       return False;
2221    end In_Unconditional_Context;
2222
2223    -------------------
2224    -- Insert_Action --
2225    -------------------
2226
2227    procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id) is
2228    begin
2229       if Present (Ins_Action) then
2230          Insert_Actions (Assoc_Node, New_List (Ins_Action));
2231       end if;
2232    end Insert_Action;
2233
2234    --  Version with check(s) suppressed
2235
2236    procedure Insert_Action
2237      (Assoc_Node : Node_Id; Ins_Action : Node_Id; Suppress : Check_Id)
2238    is
2239    begin
2240       Insert_Actions (Assoc_Node, New_List (Ins_Action), Suppress);
2241    end Insert_Action;
2242
2243    --------------------
2244    -- Insert_Actions --
2245    --------------------
2246
2247    procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id) is
2248       N : Node_Id;
2249       P : Node_Id;
2250
2251       Wrapped_Node : Node_Id := Empty;
2252
2253    begin
2254       if No (Ins_Actions) or else Is_Empty_List (Ins_Actions) then
2255          return;
2256       end if;
2257
2258       --  Ignore insert of actions from inside default expression in the
2259       --  special preliminary analyze mode. Any insertions at this point
2260       --  have no relevance, since we are only doing the analyze to freeze
2261       --  the types of any static expressions. See section "Handling of
2262       --  Default Expressions" in the spec of package Sem for further details.
2263
2264       if In_Default_Expression then
2265          return;
2266       end if;
2267
2268       --  If the action derives from stuff inside a record, then the actions
2269       --  are attached to the current scope, to be inserted and analyzed on
2270       --  exit from the scope. The reason for this is that we may also
2271       --  be generating freeze actions at the same time, and they must
2272       --  eventually be elaborated in the correct order.
2273
2274       if Is_Record_Type (Current_Scope)
2275         and then not Is_Frozen (Current_Scope)
2276       then
2277          if No (Scope_Stack.Table
2278            (Scope_Stack.Last).Pending_Freeze_Actions)
2279          then
2280             Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions :=
2281               Ins_Actions;
2282          else
2283             Append_List
2284               (Ins_Actions,
2285                Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions);
2286          end if;
2287
2288          return;
2289       end if;
2290
2291       --  We now intend to climb up the tree to find the right point to
2292       --  insert the actions. We start at Assoc_Node, unless this node is
2293       --  a subexpression in which case we start with its parent. We do this
2294       --  for two reasons. First it speeds things up. Second, if Assoc_Node
2295       --  is itself one of the special nodes like N_And_Then, then we assume
2296       --  that an initial request to insert actions for such a node does not
2297       --  expect the actions to get deposited in the node for later handling
2298       --  when the node is expanded, since clearly the node is being dealt
2299       --  with by the caller. Note that in the subexpression case, N is
2300       --  always the child we came from.
2301
2302       --  N_Raise_xxx_Error is an annoying special case, it is a statement
2303       --  if it has type Standard_Void_Type, and a subexpression otherwise.
2304       --  otherwise. Procedure attribute references are also statements.
2305
2306       if Nkind (Assoc_Node) in N_Subexpr
2307         and then (Nkind (Assoc_Node) in N_Raise_xxx_Error
2308                    or else Etype (Assoc_Node) /= Standard_Void_Type)
2309         and then (Nkind (Assoc_Node) /= N_Attribute_Reference
2310                    or else
2311                      not Is_Procedure_Attribute_Name
2312                            (Attribute_Name (Assoc_Node)))
2313       then
2314          P := Assoc_Node;             -- ??? does not agree with above!
2315          N := Parent (Assoc_Node);
2316
2317       --  Non-subexpression case. Note that N is initially Empty in this
2318       --  case (N is only guaranteed Non-Empty in the subexpr case).
2319
2320       else
2321          P := Assoc_Node;
2322          N := Empty;
2323       end if;
2324
2325       --  Capture root of the transient scope
2326
2327       if Scope_Is_Transient then
2328          Wrapped_Node := Node_To_Be_Wrapped;
2329       end if;
2330
2331       loop
2332          pragma Assert (Present (P));
2333
2334          case Nkind (P) is
2335
2336             --  Case of right operand of AND THEN or OR ELSE. Put the actions
2337             --  in the Actions field of the right operand. They will be moved
2338             --  out further when the AND THEN or OR ELSE operator is expanded.
2339             --  Nothing special needs to be done for the left operand since
2340             --  in that case the actions are executed unconditionally.
2341
2342             when N_And_Then | N_Or_Else =>
2343                if N = Right_Opnd (P) then
2344                   if Present (Actions (P)) then
2345                      Insert_List_After_And_Analyze
2346                       (Last (Actions (P)), Ins_Actions);
2347                   else
2348                      Set_Actions (P, Ins_Actions);
2349                      Analyze_List (Actions (P));
2350                   end if;
2351
2352                   return;
2353                end if;
2354
2355             --  Then or Else operand of conditional expression. Add actions to
2356             --  Then_Actions or Else_Actions field as appropriate. The actions
2357             --  will be moved further out when the conditional is expanded.
2358
2359             when N_Conditional_Expression =>
2360                declare
2361                   ThenX : constant Node_Id := Next (First (Expressions (P)));
2362                   ElseX : constant Node_Id := Next (ThenX);
2363
2364                begin
2365                   --  Actions belong to the then expression, temporarily
2366                   --  place them as Then_Actions of the conditional expr.
2367                   --  They will be moved to the proper place later when
2368                   --  the conditional expression is expanded.
2369
2370                   if N = ThenX then
2371                      if Present (Then_Actions (P)) then
2372                         Insert_List_After_And_Analyze
2373                           (Last (Then_Actions (P)), Ins_Actions);
2374                      else
2375                         Set_Then_Actions (P, Ins_Actions);
2376                         Analyze_List (Then_Actions (P));
2377                      end if;
2378
2379                      return;
2380
2381                   --  Actions belong to the else expression, temporarily
2382                   --  place them as Else_Actions of the conditional expr.
2383                   --  They will be moved to the proper place later when
2384                   --  the conditional expression is expanded.
2385
2386                   elsif N = ElseX then
2387                      if Present (Else_Actions (P)) then
2388                         Insert_List_After_And_Analyze
2389                           (Last (Else_Actions (P)), Ins_Actions);
2390                      else
2391                         Set_Else_Actions (P, Ins_Actions);
2392                         Analyze_List (Else_Actions (P));
2393                      end if;
2394
2395                      return;
2396
2397                   --  Actions belong to the condition. In this case they are
2398                   --  unconditionally executed, and so we can continue the
2399                   --  search for the proper insert point.
2400
2401                   else
2402                      null;
2403                   end if;
2404                end;
2405
2406             --  Case of appearing in the condition of a while expression or
2407             --  elsif. We insert the actions into the Condition_Actions field.
2408             --  They will be moved further out when the while loop or elsif
2409             --  is analyzed.
2410
2411             when N_Iteration_Scheme |
2412                  N_Elsif_Part
2413             =>
2414                if N = Condition (P) then
2415                   if Present (Condition_Actions (P)) then
2416                      Insert_List_After_And_Analyze
2417                        (Last (Condition_Actions (P)), Ins_Actions);
2418                   else
2419                      Set_Condition_Actions (P, Ins_Actions);
2420
2421                      --  Set the parent of the insert actions explicitly.
2422                      --  This is not a syntactic field, but we need the
2423                      --  parent field set, in particular so that freeze
2424                      --  can understand that it is dealing with condition
2425                      --  actions, and properly insert the freezing actions.
2426
2427                      Set_Parent (Ins_Actions, P);
2428                      Analyze_List (Condition_Actions (P));
2429                   end if;
2430
2431                   return;
2432                end if;
2433
2434             --  Statements, declarations, pragmas, representation clauses
2435
2436             when
2437                --  Statements
2438
2439                N_Procedure_Call_Statement               |
2440                N_Statement_Other_Than_Procedure_Call    |
2441
2442                --  Pragmas
2443
2444                N_Pragma                                 |
2445
2446                --  Representation_Clause
2447
2448                N_At_Clause                              |
2449                N_Attribute_Definition_Clause            |
2450                N_Enumeration_Representation_Clause      |
2451                N_Record_Representation_Clause           |
2452
2453                --  Declarations
2454
2455                N_Abstract_Subprogram_Declaration        |
2456                N_Entry_Body                             |
2457                N_Exception_Declaration                  |
2458                N_Exception_Renaming_Declaration         |
2459                N_Formal_Abstract_Subprogram_Declaration |
2460                N_Formal_Concrete_Subprogram_Declaration |
2461                N_Formal_Object_Declaration              |
2462                N_Formal_Type_Declaration                |
2463                N_Full_Type_Declaration                  |
2464                N_Function_Instantiation                 |
2465                N_Generic_Function_Renaming_Declaration  |
2466                N_Generic_Package_Declaration            |
2467                N_Generic_Package_Renaming_Declaration   |
2468                N_Generic_Procedure_Renaming_Declaration |
2469                N_Generic_Subprogram_Declaration         |
2470                N_Implicit_Label_Declaration             |
2471                N_Incomplete_Type_Declaration            |
2472                N_Number_Declaration                     |
2473                N_Object_Declaration                     |
2474                N_Object_Renaming_Declaration            |
2475                N_Package_Body                           |
2476                N_Package_Body_Stub                      |
2477                N_Package_Declaration                    |
2478                N_Package_Instantiation                  |
2479                N_Package_Renaming_Declaration           |
2480                N_Private_Extension_Declaration          |
2481                N_Private_Type_Declaration               |
2482                N_Procedure_Instantiation                |
2483                N_Protected_Body_Stub                    |
2484                N_Protected_Type_Declaration             |
2485                N_Single_Task_Declaration                |
2486                N_Subprogram_Body                        |
2487                N_Subprogram_Body_Stub                   |
2488                N_Subprogram_Declaration                 |
2489                N_Subprogram_Renaming_Declaration        |
2490                N_Subtype_Declaration                    |
2491                N_Task_Body                              |
2492                N_Task_Body_Stub                         |
2493                N_Task_Type_Declaration                  |
2494
2495                --  Freeze entity behaves like a declaration or statement
2496
2497                N_Freeze_Entity
2498             =>
2499                --  Do not insert here if the item is not a list member (this
2500                --  happens for example with a triggering statement, and the
2501                --  proper approach is to insert before the entire select).
2502
2503                if not Is_List_Member (P) then
2504                   null;
2505
2506                --  Do not insert if parent of P is an N_Component_Association
2507                --  node (i.e. we are in the context of an N_Aggregate or
2508                --  N_Extension_Aggregate node. In this case we want to insert
2509                --  before the entire aggregate.
2510
2511                elsif Nkind (Parent (P)) = N_Component_Association then
2512                   null;
2513
2514                --  Do not insert if the parent of P is either an N_Variant
2515                --  node or an N_Record_Definition node, meaning in either
2516                --  case that P is a member of a component list, and that
2517                --  therefore the actions should be inserted outside the
2518                --  complete record declaration.
2519
2520                elsif Nkind (Parent (P)) = N_Variant
2521                  or else Nkind (Parent (P)) = N_Record_Definition
2522                then
2523                   null;
2524
2525                --  Do not insert freeze nodes within the loop generated for
2526                --  an aggregate, because they may be elaborated too late for
2527                --  subsequent use in the back end: within a package spec the
2528                --  loop is part of the elaboration procedure and is only
2529                --  elaborated during the second pass.
2530                --  If the loop comes from source, or the entity is local to
2531                --  the loop itself it must remain within.
2532
2533                elsif Nkind (Parent (P)) = N_Loop_Statement
2534                  and then not Comes_From_Source (Parent (P))
2535                  and then Nkind (First (Ins_Actions)) = N_Freeze_Entity
2536                  and then
2537                    Scope (Entity (First (Ins_Actions))) /= Current_Scope
2538                then
2539                   null;
2540
2541                --  Otherwise we can go ahead and do the insertion
2542
2543                elsif P = Wrapped_Node then
2544                   Store_Before_Actions_In_Scope (Ins_Actions);
2545                   return;
2546
2547                else
2548                   Insert_List_Before_And_Analyze (P, Ins_Actions);
2549                   return;
2550                end if;
2551
2552             --  A special case, N_Raise_xxx_Error can act either as a
2553             --  statement or a subexpression. We tell the difference
2554             --  by looking at the Etype. It is set to Standard_Void_Type
2555             --  in the statement case.
2556
2557             when
2558                N_Raise_xxx_Error =>
2559                   if Etype (P) = Standard_Void_Type then
2560                      if  P = Wrapped_Node then
2561                         Store_Before_Actions_In_Scope (Ins_Actions);
2562                      else
2563                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2564                      end if;
2565
2566                      return;
2567
2568                   --  In the subexpression case, keep climbing
2569
2570                   else
2571                      null;
2572                   end if;
2573
2574             --  If a component association appears within a loop created for
2575             --  an array aggregate, attach the actions to the association so
2576             --  they can be subsequently inserted within the loop. For other
2577             --  component associations insert outside of the aggregate. For
2578             --  an association that will generate a loop, its Loop_Actions
2579             --  attribute is already initialized (see exp_aggr.adb).
2580
2581             --  The list of loop_actions can in turn generate additional ones,
2582             --  that are inserted before the associated node. If the associated
2583             --  node is outside the aggregate, the new actions are collected
2584             --  at the end of the loop actions, to respect the order in which
2585             --  they are to be elaborated.
2586
2587             when
2588                N_Component_Association =>
2589                   if Nkind (Parent (P)) = N_Aggregate
2590                     and then Present (Loop_Actions (P))
2591                   then
2592                      if Is_Empty_List (Loop_Actions (P)) then
2593                         Set_Loop_Actions (P, Ins_Actions);
2594                         Analyze_List (Ins_Actions);
2595
2596                      else
2597                         declare
2598                            Decl : Node_Id;
2599
2600                         begin
2601                            --  Check whether these actions were generated
2602                            --  by a declaration that is part of the loop_
2603                            --  actions for the component_association.
2604
2605                            Decl := Assoc_Node;
2606                            while Present (Decl) loop
2607                               exit when Parent (Decl) = P
2608                                 and then Is_List_Member (Decl)
2609                                 and then
2610                                   List_Containing (Decl) = Loop_Actions (P);
2611                               Decl := Parent (Decl);
2612                            end loop;
2613
2614                            if Present (Decl) then
2615                               Insert_List_Before_And_Analyze
2616                                 (Decl, Ins_Actions);
2617                            else
2618                               Insert_List_After_And_Analyze
2619                                 (Last (Loop_Actions (P)), Ins_Actions);
2620                            end if;
2621                         end;
2622                      end if;
2623
2624                      return;
2625
2626                   else
2627                      null;
2628                   end if;
2629
2630             --  Another special case, an attribute denoting a procedure call
2631
2632             when
2633                N_Attribute_Reference =>
2634                   if Is_Procedure_Attribute_Name (Attribute_Name (P)) then
2635                      if P = Wrapped_Node then
2636                         Store_Before_Actions_In_Scope (Ins_Actions);
2637                      else
2638                         Insert_List_Before_And_Analyze (P, Ins_Actions);
2639                      end if;
2640
2641                      return;
2642
2643                   --  In the subexpression case, keep climbing
2644
2645                   else
2646                      null;
2647                   end if;
2648
2649             --  For all other node types, keep climbing tree
2650
2651             when
2652                N_Abortable_Part                         |
2653                N_Accept_Alternative                     |
2654                N_Access_Definition                      |
2655                N_Access_Function_Definition             |
2656                N_Access_Procedure_Definition            |
2657                N_Access_To_Object_Definition            |
2658                N_Aggregate                              |
2659                N_Allocator                              |
2660                N_Case_Statement_Alternative             |
2661                N_Character_Literal                      |
2662                N_Compilation_Unit                       |
2663                N_Compilation_Unit_Aux                   |
2664                N_Component_Clause                       |
2665                N_Component_Declaration                  |
2666                N_Component_Definition                   |
2667                N_Component_List                         |
2668                N_Constrained_Array_Definition           |
2669                N_Decimal_Fixed_Point_Definition         |
2670                N_Defining_Character_Literal             |
2671                N_Defining_Identifier                    |
2672                N_Defining_Operator_Symbol               |
2673                N_Defining_Program_Unit_Name             |
2674                N_Delay_Alternative                      |
2675                N_Delta_Constraint                       |
2676                N_Derived_Type_Definition                |
2677                N_Designator                             |
2678                N_Digits_Constraint                      |
2679                N_Discriminant_Association               |
2680                N_Discriminant_Specification             |
2681                N_Empty                                  |
2682                N_Entry_Body_Formal_Part                 |
2683                N_Entry_Call_Alternative                 |
2684                N_Entry_Declaration                      |
2685                N_Entry_Index_Specification              |
2686                N_Enumeration_Type_Definition            |
2687                N_Error                                  |
2688                N_Exception_Handler                      |
2689                N_Expanded_Name                          |
2690                N_Explicit_Dereference                   |
2691                N_Extension_Aggregate                    |
2692                N_Floating_Point_Definition              |
2693                N_Formal_Decimal_Fixed_Point_Definition  |
2694                N_Formal_Derived_Type_Definition         |
2695                N_Formal_Discrete_Type_Definition        |
2696                N_Formal_Floating_Point_Definition       |
2697                N_Formal_Modular_Type_Definition         |
2698                N_Formal_Ordinary_Fixed_Point_Definition |
2699                N_Formal_Package_Declaration             |
2700                N_Formal_Private_Type_Definition         |
2701                N_Formal_Signed_Integer_Type_Definition  |
2702                N_Function_Call                          |
2703                N_Function_Specification                 |
2704                N_Generic_Association                    |
2705                N_Handled_Sequence_Of_Statements         |
2706                N_Identifier                             |
2707                N_In                                     |
2708                N_Index_Or_Discriminant_Constraint       |
2709                N_Indexed_Component                      |
2710                N_Integer_Literal                        |
2711                N_Itype_Reference                        |
2712                N_Label                                  |
2713                N_Loop_Parameter_Specification           |
2714                N_Mod_Clause                             |
2715                N_Modular_Type_Definition                |
2716                N_Not_In                                 |
2717                N_Null                                   |
2718                N_Op_Abs                                 |
2719                N_Op_Add                                 |
2720                N_Op_And                                 |
2721                N_Op_Concat                              |
2722                N_Op_Divide                              |
2723                N_Op_Eq                                  |
2724                N_Op_Expon                               |
2725                N_Op_Ge                                  |
2726                N_Op_Gt                                  |
2727                N_Op_Le                                  |
2728                N_Op_Lt                                  |
2729                N_Op_Minus                               |
2730                N_Op_Mod                                 |
2731                N_Op_Multiply                            |
2732                N_Op_Ne                                  |
2733                N_Op_Not                                 |
2734                N_Op_Or                                  |
2735                N_Op_Plus                                |
2736                N_Op_Rem                                 |
2737                N_Op_Rotate_Left                         |
2738                N_Op_Rotate_Right                        |
2739                N_Op_Shift_Left                          |
2740                N_Op_Shift_Right                         |
2741                N_Op_Shift_Right_Arithmetic              |
2742                N_Op_Subtract                            |
2743                N_Op_Xor                                 |
2744                N_Operator_Symbol                        |
2745                N_Ordinary_Fixed_Point_Definition        |
2746                N_Others_Choice                          |
2747                N_Package_Specification                  |
2748                N_Parameter_Association                  |
2749                N_Parameter_Specification                |
2750                N_Pragma_Argument_Association            |
2751                N_Procedure_Specification                |
2752                N_Protected_Body                         |
2753                N_Protected_Definition                   |
2754                N_Qualified_Expression                   |
2755                N_Range                                  |
2756                N_Range_Constraint                       |
2757                N_Real_Literal                           |
2758                N_Real_Range_Specification               |
2759                N_Record_Definition                      |
2760                N_Reference                              |
2761                N_Selected_Component                     |
2762                N_Signed_Integer_Type_Definition         |
2763                N_Single_Protected_Declaration           |
2764                N_Slice                                  |
2765                N_String_Literal                         |
2766                N_Subprogram_Info                        |
2767                N_Subtype_Indication                     |
2768                N_Subunit                                |
2769                N_Task_Definition                        |
2770                N_Terminate_Alternative                  |
2771                N_Triggering_Alternative                 |
2772                N_Type_Conversion                        |
2773                N_Unchecked_Expression                   |
2774                N_Unchecked_Type_Conversion              |
2775                N_Unconstrained_Array_Definition         |
2776                N_Unused_At_End                          |
2777                N_Unused_At_Start                        |
2778                N_Use_Package_Clause                     |
2779                N_Use_Type_Clause                        |
2780                N_Variant                                |
2781                N_Variant_Part                           |
2782                N_Validate_Unchecked_Conversion          |
2783                N_With_Clause                            |
2784                N_With_Type_Clause
2785             =>
2786                null;
2787
2788          end case;
2789
2790          --  Make sure that inserted actions stay in the transient scope
2791
2792          if P = Wrapped_Node then
2793             Store_Before_Actions_In_Scope (Ins_Actions);
2794             return;
2795          end if;
2796
2797          --  If we fall through above tests, keep climbing tree
2798
2799          N := P;
2800
2801          if Nkind (Parent (N)) = N_Subunit then
2802
2803             --  This is the proper body corresponding to a stub. Insertion
2804             --  must be done at the point of the stub, which is in the decla-
2805             --  tive part of the parent unit.
2806
2807             P := Corresponding_Stub (Parent (N));
2808
2809          else
2810             P := Parent (N);
2811          end if;
2812       end loop;
2813
2814    end Insert_Actions;
2815
2816    --  Version with check(s) suppressed
2817
2818    procedure Insert_Actions
2819      (Assoc_Node : Node_Id; Ins_Actions : List_Id; Suppress : Check_Id)
2820    is
2821    begin
2822       if Suppress = All_Checks then
2823          declare
2824             Svg : constant Suppress_Array := Scope_Suppress;
2825          begin
2826             Scope_Suppress := (others => True);
2827             Insert_Actions (Assoc_Node, Ins_Actions);
2828             Scope_Suppress := Svg;
2829          end;
2830
2831       else
2832          declare
2833             Svg : constant Boolean := Scope_Suppress (Suppress);
2834          begin
2835             Scope_Suppress (Suppress) := True;
2836             Insert_Actions (Assoc_Node, Ins_Actions);
2837             Scope_Suppress (Suppress) := Svg;
2838          end;
2839       end if;
2840    end Insert_Actions;
2841
2842    --------------------------
2843    -- Insert_Actions_After --
2844    --------------------------
2845
2846    procedure Insert_Actions_After
2847      (Assoc_Node  : Node_Id;
2848       Ins_Actions : List_Id)
2849    is
2850    begin
2851       if Scope_Is_Transient
2852         and then Assoc_Node = Node_To_Be_Wrapped
2853       then
2854          Store_After_Actions_In_Scope (Ins_Actions);
2855       else
2856          Insert_List_After_And_Analyze (Assoc_Node, Ins_Actions);
2857       end if;
2858    end Insert_Actions_After;
2859
2860    ---------------------------------
2861    -- Insert_Library_Level_Action --
2862    ---------------------------------
2863
2864    procedure Insert_Library_Level_Action (N : Node_Id) is
2865       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2866
2867    begin
2868       New_Scope (Cunit_Entity (Main_Unit));
2869
2870       if No (Actions (Aux)) then
2871          Set_Actions (Aux, New_List (N));
2872       else
2873          Append (N, Actions (Aux));
2874       end if;
2875
2876       Analyze (N);
2877       Pop_Scope;
2878    end Insert_Library_Level_Action;
2879
2880    ----------------------------------
2881    -- Insert_Library_Level_Actions --
2882    ----------------------------------
2883
2884    procedure Insert_Library_Level_Actions (L : List_Id) is
2885       Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit));
2886
2887    begin
2888       if Is_Non_Empty_List (L) then
2889          New_Scope (Cunit_Entity (Main_Unit));
2890
2891          if No (Actions (Aux)) then
2892             Set_Actions (Aux, L);
2893             Analyze_List (L);
2894          else
2895             Insert_List_After_And_Analyze (Last (Actions (Aux)), L);
2896          end if;
2897
2898          Pop_Scope;
2899       end if;
2900    end Insert_Library_Level_Actions;
2901
2902    ----------------------
2903    -- Inside_Init_Proc --
2904    ----------------------
2905
2906    function Inside_Init_Proc return Boolean is
2907       S : Entity_Id;
2908
2909    begin
2910       S := Current_Scope;
2911       while Present (S)
2912         and then S /= Standard_Standard
2913       loop
2914          if Is_Init_Proc (S) then
2915             return True;
2916          else
2917             S := Scope (S);
2918          end if;
2919       end loop;
2920
2921       return False;
2922    end Inside_Init_Proc;
2923
2924    ----------------------------
2925    -- Is_All_Null_Statements --
2926    ----------------------------
2927
2928    function Is_All_Null_Statements (L : List_Id) return Boolean is
2929       Stm : Node_Id;
2930
2931    begin
2932       Stm := First (L);
2933       while Present (Stm) loop
2934          if Nkind (Stm) /= N_Null_Statement then
2935             return False;
2936          end if;
2937
2938          Next (Stm);
2939       end loop;
2940
2941       return True;
2942    end Is_All_Null_Statements;
2943
2944    -----------------------------------------
2945    -- Is_Predefined_Dispatching_Operation --
2946    -----------------------------------------
2947
2948    function Is_Predefined_Dispatching_Operation (E : Entity_Id) return Boolean
2949    is
2950       TSS_Name : TSS_Name_Type;
2951
2952    begin
2953       if not Is_Dispatching_Operation (E) then
2954          return False;
2955       end if;
2956
2957       Get_Name_String (Chars (E));
2958
2959       if Name_Len > TSS_Name_Type'Last then
2960          TSS_Name := TSS_Name_Type (Name_Buffer (Name_Len - TSS_Name'Length + 1
2961                                      .. Name_Len));
2962          if Chars (E)        = Name_uSize
2963            or else Chars (E) = Name_uAlignment
2964            or else TSS_Name  = TSS_Stream_Read
2965            or else TSS_Name  = TSS_Stream_Write
2966            or else TSS_Name  = TSS_Stream_Input
2967            or else TSS_Name  = TSS_Stream_Output
2968            or else
2969              (Chars (E) = Name_Op_Eq
2970                 and then Etype (First_Entity (E)) = Etype (Last_Entity (E)))
2971            or else Chars (E) = Name_uAssign
2972            or else TSS_Name  = TSS_Deep_Adjust
2973            or else TSS_Name  = TSS_Deep_Finalize
2974            or else (Ada_Version >= Ada_05
2975              and then (Chars (E) = Name_uDisp_Asynchronous_Select
2976                or else Chars (E) = Name_uDisp_Conditional_Select
2977                or else Chars (E) = Name_uDisp_Get_Prim_Op_Kind
2978                or else Chars (E) = Name_uDisp_Get_Task_Id
2979                or else Chars (E) = Name_uDisp_Timed_Select))
2980          then
2981             return True;
2982          end if;
2983       end if;
2984
2985       return False;
2986    end Is_Predefined_Dispatching_Operation;
2987
2988    ----------------------------------
2989    -- Is_Possibly_Unaligned_Object --
2990    ----------------------------------
2991
2992    function Is_Possibly_Unaligned_Object (N : Node_Id) return Boolean is
2993       T  : constant Entity_Id := Etype (N);
2994
2995    begin
2996       --  If renamed object, apply test to underlying object
2997
2998       if Is_Entity_Name (N)
2999         and then Is_Object (Entity (N))
3000         and then Present (Renamed_Object (Entity (N)))
3001       then
3002          return Is_Possibly_Unaligned_Object (Renamed_Object (Entity (N)));
3003       end if;
3004
3005       --  Tagged and controlled types and aliased types are always aligned,
3006       --  as are concurrent types.
3007
3008       if Is_Aliased (T)
3009         or else Has_Controlled_Component (T)
3010         or else Is_Concurrent_Type (T)
3011         or else Is_Tagged_Type (T)
3012         or else Is_Controlled (T)
3013       then
3014          return False;
3015       end if;
3016
3017       --  If this is an element of a packed array, may be unaligned
3018
3019       if Is_Ref_To_Bit_Packed_Array (N) then
3020          return True;
3021       end if;
3022
3023       --  Case of component reference
3024
3025       if Nkind (N) = N_Selected_Component then
3026          declare
3027             P : constant Node_Id   := Prefix (N);
3028             C : constant Entity_Id := Entity (Selector_Name (N));
3029             M : Nat;
3030             S : Nat;
3031
3032          begin
3033             --  If component reference is for an array with non-static bounds,
3034             --  then it is always aligned: we can only process unaligned
3035             --  arrays with static bounds (more accurately bounds known at
3036             --  compile time).
3037
3038             if Is_Array_Type (T)
3039               and then not Compile_Time_Known_Bounds (T)
3040             then
3041                return False;
3042             end if;
3043
3044             --  If component is aliased, it is definitely properly aligned
3045
3046             if Is_Aliased (C) then
3047                return False;
3048             end if;
3049
3050             --  If component is for a type implemented as a scalar, and the
3051             --  record is packed, and the component is other than the first
3052             --  component of the record, then the component may be unaligned.
3053
3054             if Is_Packed (Etype (P))
3055               and then Represented_As_Scalar (Etype (C))
3056               and then First_Entity (Scope (C)) /= C
3057             then
3058                return True;
3059             end if;
3060
3061             --  Compute maximum possible alignment for T
3062
3063             --  If alignment is known, then that settles things
3064
3065             if Known_Alignment (T) then
3066                M := UI_To_Int (Alignment (T));
3067
3068             --  If alignment is not known, tentatively set max alignment
3069
3070             else
3071                M := Ttypes.Maximum_Alignment;
3072
3073                --  We can reduce this if the Esize is known since the default
3074                --  alignment will never be more than the smallest power of 2
3075                --  that does not exceed this Esize value.
3076
3077                if Known_Esize (T) then
3078                   S := UI_To_Int (Esize (T));
3079
3080                   while (M / 2) >= S loop
3081                      M := M / 2;
3082                   end loop;
3083                end if;
3084             end if;
3085
3086             --  If the component reference is for a record that has a specified
3087             --  alignment, and we either know it is too small, or cannot tell,
3088             --  then the component may be unaligned
3089
3090             if Known_Alignment (Etype (P))
3091               and then Alignment (Etype (P)) < Ttypes.Maximum_Alignment
3092               and then M > Alignment (Etype (P))
3093             then
3094                return True;
3095             end if;
3096
3097             --  Case of component clause present which may specify an
3098             --  unaligned position.
3099
3100             if Present (Component_Clause (C)) then
3101
3102                --  Otherwise we can do a test to make sure that the actual
3103                --  start position in the record, and the length, are both
3104                --  consistent with the required alignment. If not, we know
3105                --  that we are unaligned.
3106
3107                declare
3108                   Align_In_Bits : constant Nat := M * System_Storage_Unit;
3109                begin
3110                   if Component_Bit_Offset (C) mod Align_In_Bits /= 0
3111                     or else Esize (C) mod Align_In_Bits /= 0
3112                   then
3113                      return True;
3114                   end if;
3115                end;
3116             end if;
3117
3118             --  Otherwise, for a component reference, test prefix
3119
3120             return Is_Possibly_Unaligned_Object (P);
3121          end;
3122
3123       --  If not a component reference, must be aligned
3124
3125       else
3126          return False;
3127       end if;
3128    end Is_Possibly_Unaligned_Object;
3129
3130    ---------------------------------
3131    -- Is_Possibly_Unaligned_Slice --
3132    ---------------------------------
3133
3134    function Is_Possibly_Unaligned_Slice (N : Node_Id) return Boolean is
3135    begin
3136       --  ??? GCC3 will eventually handle strings with arbitrary alignments,
3137       --  but for now the following check must be disabled.
3138
3139       --  if get_gcc_version >= 3 then
3140       --     return False;
3141       --  end if;
3142
3143       --  For renaming case, go to renamed object
3144
3145       if Is_Entity_Name (N)
3146         and then Is_Object (Entity (N))
3147         and then Present (Renamed_Object (Entity (N)))
3148       then
3149          return Is_Possibly_Unaligned_Slice (Renamed_Object (Entity (N)));
3150       end if;
3151
3152       --  The reference must be a slice
3153
3154       if Nkind (N) /= N_Slice then
3155          return False;
3156       end if;
3157
3158       --  Always assume the worst for a nested record component with a
3159       --  component clause, which gigi/gcc does not appear to handle well.
3160       --  It is not clear why this special test is needed at all ???
3161
3162       if Nkind (Prefix (N)) = N_Selected_Component
3163         and then Nkind (Prefix (Prefix (N))) = N_Selected_Component
3164         and then
3165           Present (Component_Clause (Entity (Selector_Name (Prefix (N)))))
3166       then
3167          return True;
3168       end if;
3169
3170       --  We only need to worry if the target has strict alignment
3171
3172       if not Target_Strict_Alignment then
3173          return False;
3174       end if;
3175
3176       --  If it is a slice, then look at the array type being sliced
3177
3178       declare
3179          Sarr : constant Node_Id := Prefix (N);
3180          --  Prefix of the slice, i.e. the array being sliced
3181
3182          Styp : constant Entity_Id := Etype (Prefix (N));
3183          --  Type of the array being sliced
3184
3185          Pref : Node_Id;
3186          Ptyp : Entity_Id;
3187
3188       begin
3189          --  The problems arise if the array object that is being sliced
3190          --  is a component of a record or array, and we cannot guarantee
3191          --  the alignment of the array within its containing object.
3192
3193          --  To investigate this, we look at successive prefixes to see
3194          --  if we have a worrisome indexed or selected component.
3195
3196          Pref := Sarr;
3197          loop
3198             --  Case of array is part of an indexed component reference
3199
3200             if Nkind (Pref) = N_Indexed_Component then
3201                Ptyp := Etype (Prefix (Pref));
3202
3203                --  The only problematic case is when the array is packed,
3204                --  in which case we really know nothing about the alignment
3205                --  of individual components.
3206
3207                if Is_Bit_Packed_Array (Ptyp) then
3208                   return True;
3209                end if;
3210
3211             --  Case of array is part of a selected component reference
3212
3213             elsif Nkind (Pref) = N_Selected_Component then
3214                Ptyp := Etype (Prefix (Pref));
3215
3216                --  We are definitely in trouble if the record in question
3217                --  has an alignment, and either we know this alignment is
3218                --  inconsistent with the alignment of the slice, or we
3219                --  don't know what the alignment of the slice should be.
3220
3221                if Known_Alignment (Ptyp)
3222                  and then (Unknown_Alignment (Styp)
3223                              or else Alignment (Styp) > Alignment (Ptyp))
3224                then
3225                   return True;
3226                end if;
3227
3228                --  We are in potential trouble if the record type is packed.
3229                --  We could special case when we know that the array is the
3230                --  first component, but that's not such a simple case ???
3231
3232                if Is_Packed (Ptyp) then
3233                   return True;
3234                end if;
3235
3236                --  We are in trouble if there is a component clause, and
3237                --  either we do not know the alignment of the slice, or
3238                --  the alignment of the slice is inconsistent with the
3239                --  bit position specified by the component clause.
3240
3241                declare
3242                   Field : constant Entity_Id := Entity (Selector_Name (Pref));
3243                begin
3244                   if Present (Component_Clause (Field))
3245                     and then
3246                       (Unknown_Alignment (Styp)
3247                         or else
3248                          (Component_Bit_Offset (Field) mod
3249                            (System_Storage_Unit * Alignment (Styp))) /= 0)
3250                   then
3251                      return True;
3252                   end if;
3253                end;
3254
3255             --  For cases other than selected or indexed components we
3256             --  know we are OK, since no issues arise over alignment.
3257
3258             else
3259                return False;
3260             end if;
3261
3262             --  We processed an indexed component or selected component
3263             --  reference that looked safe, so keep checking prefixes.
3264
3265             Pref := Prefix (Pref);
3266          end loop;
3267       end;
3268    end Is_Possibly_Unaligned_Slice;
3269
3270    --------------------------------
3271    -- Is_Ref_To_Bit_Packed_Array --
3272    --------------------------------
3273
3274    function Is_Ref_To_Bit_Packed_Array (N : Node_Id) return Boolean is
3275       Result : Boolean;
3276       Expr   : Node_Id;
3277
3278    begin
3279       if Is_Entity_Name (N)
3280         and then Is_Object (Entity (N))
3281         and then Present (Renamed_Object (Entity (N)))
3282       then
3283          return Is_Ref_To_Bit_Packed_Array (Renamed_Object (Entity (N)));
3284       end if;
3285
3286       if Nkind (N) = N_Indexed_Component
3287            or else
3288          Nkind (N) = N_Selected_Component
3289       then
3290          if Is_Bit_Packed_Array (Etype (Prefix (N))) then
3291             Result := True;
3292          else
3293             Result := Is_Ref_To_Bit_Packed_Array (Prefix (N));
3294          end if;
3295
3296          if Result and then Nkind (N) = N_Indexed_Component then
3297             Expr := First (Expressions (N));
3298             while Present (Expr) loop
3299                Force_Evaluation (Expr);
3300                Next (Expr);
3301             end loop;
3302          end if;
3303
3304          return Result;
3305
3306       else
3307          return False;
3308       end if;
3309    end Is_Ref_To_Bit_Packed_Array;
3310
3311    --------------------------------
3312    -- Is_Ref_To_Bit_Packed_Slice --
3313    --------------------------------
3314
3315    function Is_Ref_To_Bit_Packed_Slice (N : Node_Id) return Boolean is
3316    begin
3317       if Nkind (N) = N_Type_Conversion then
3318          return Is_Ref_To_Bit_Packed_Slice (Expression (N));
3319
3320       elsif Is_Entity_Name (N)
3321         and then Is_Object (Entity (N))
3322         and then Present (Renamed_Object (Entity (N)))
3323       then
3324          return Is_Ref_To_Bit_Packed_Slice (Renamed_Object (Entity (N)));
3325
3326       elsif Nkind (N) = N_Slice
3327         and then Is_Bit_Packed_Array (Etype (Prefix (N)))
3328       then
3329          return True;
3330
3331       elsif Nkind (N) = N_Indexed_Component
3332            or else
3333          Nkind (N) = N_Selected_Component
3334       then
3335          return Is_Ref_To_Bit_Packed_Slice (Prefix (N));
3336
3337       else
3338          return False;
3339       end if;
3340    end Is_Ref_To_Bit_Packed_Slice;
3341
3342    -----------------------
3343    -- Is_Renamed_Object --
3344    -----------------------
3345
3346    function Is_Renamed_Object (N : Node_Id) return Boolean is
3347       Pnod : constant Node_Id   := Parent (N);
3348       Kind : constant Node_Kind := Nkind (Pnod);
3349
3350    begin
3351       if Kind = N_Object_Renaming_Declaration then
3352          return True;
3353
3354       elsif Kind = N_Indexed_Component
3355         or else Kind = N_Selected_Component
3356       then
3357          return Is_Renamed_Object (Pnod);
3358
3359       else
3360          return False;
3361       end if;
3362    end Is_Renamed_Object;
3363
3364    ----------------------------
3365    -- Is_Untagged_Derivation --
3366    ----------------------------
3367
3368    function Is_Untagged_Derivation (T : Entity_Id) return Boolean is
3369    begin
3370       return (not Is_Tagged_Type (T) and then Is_Derived_Type (T))
3371                or else
3372              (Is_Private_Type (T) and then Present (Full_View (T))
3373                and then not Is_Tagged_Type (Full_View (T))
3374                and then Is_Derived_Type (Full_View (T))
3375                and then Etype (Full_View (T)) /= T);
3376    end Is_Untagged_Derivation;
3377
3378    --------------------
3379    -- Kill_Dead_Code --
3380    --------------------
3381
3382    procedure Kill_Dead_Code (N : Node_Id; Warn : Boolean := False) is
3383    begin
3384       if Present (N) then
3385          Remove_Warning_Messages (N);
3386
3387          if Warn then
3388             Error_Msg_F
3389               ("?this code can never be executed and has been deleted", N);
3390          end if;
3391
3392          --  Recurse into block statements and bodies to process declarations
3393          --  and statements
3394
3395          if Nkind (N) = N_Block_Statement
3396            or else Nkind (N) = N_Subprogram_Body
3397            or else Nkind (N) = N_Package_Body
3398          then
3399             Kill_Dead_Code
3400               (Declarations (N), False);
3401             Kill_Dead_Code
3402               (Statements (Handled_Statement_Sequence (N)));
3403
3404             if Nkind (N) = N_Subprogram_Body then
3405                Set_Is_Eliminated (Defining_Entity (N));
3406             end if;
3407
3408          elsif Nkind (N) = N_Package_Declaration then
3409             Kill_Dead_Code (Visible_Declarations (Specification (N)));
3410             Kill_Dead_Code (Private_Declarations (Specification (N)));
3411
3412             declare
3413                E : Entity_Id := First_Entity (Defining_Entity (N));
3414             begin
3415                while Present (E) loop
3416                   if Ekind (E) = E_Operator then
3417                      Set_Is_Eliminated (E);
3418                   end if;
3419
3420                   Next_Entity (E);
3421                end loop;
3422             end;
3423
3424          --  Recurse into composite statement to kill individual statements,
3425          --  in particular instantiations.
3426
3427          elsif Nkind (N) = N_If_Statement then
3428             Kill_Dead_Code (Then_Statements (N));
3429             Kill_Dead_Code (Elsif_Parts (N));
3430             Kill_Dead_Code (Else_Statements (N));
3431
3432          elsif Nkind (N) = N_Loop_Statement then
3433             Kill_Dead_Code (Statements (N));
3434
3435          elsif Nkind (N) = N_Case_Statement then
3436             declare
3437                Alt : Node_Id;
3438             begin
3439                Alt := First (Alternatives (N));
3440                while Present (Alt) loop
3441                   Kill_Dead_Code (Statements (Alt));
3442                   Next (Alt);
3443                end loop;
3444             end;
3445
3446          elsif Nkind (N) = N_Case_Statement_Alternative then
3447             Kill_Dead_Code (Statements (N));
3448
3449          --  Deal with dead instances caused by deleting instantiations
3450
3451          elsif Nkind (N) in N_Generic_Instantiation then
3452             Remove_Dead_Instance (N);
3453          end if;
3454
3455          Delete_Tree (N);
3456       end if;
3457    end Kill_Dead_Code;
3458
3459    --  Case where argument is a list of nodes to be killed
3460
3461    procedure Kill_Dead_Code (L : List_Id; Warn : Boolean := False) is
3462       N : Node_Id;
3463       W : Boolean;
3464    begin
3465       W := Warn;
3466       if Is_Non_Empty_List (L) then
3467          loop
3468             N := Remove_Head (L);
3469             exit when No (N);
3470             Kill_Dead_Code (N, W);
3471             W := False;
3472          end loop;
3473       end if;
3474    end Kill_Dead_Code;
3475
3476    ------------------------
3477    -- Known_Non_Negative --
3478    ------------------------
3479
3480    function Known_Non_Negative (Opnd : Node_Id) return Boolean is
3481    begin
3482       if Is_OK_Static_Expression (Opnd)
3483         and then Expr_Value (Opnd) >= 0
3484       then
3485          return True;
3486
3487       else
3488          declare
3489             Lo : constant Node_Id := Type_Low_Bound (Etype (Opnd));
3490
3491          begin
3492             return
3493               Is_OK_Static_Expression (Lo) and then Expr_Value (Lo) >= 0;
3494          end;
3495       end if;
3496    end Known_Non_Negative;
3497
3498    --------------------
3499    -- Known_Non_Null --
3500    --------------------
3501
3502    function Known_Non_Null (N : Node_Id) return Boolean is
3503    begin
3504       --  Checks for case where N is an entity reference
3505
3506       if Is_Entity_Name (N) and then Present (Entity (N)) then
3507          declare
3508             E   : constant Entity_Id := Entity (N);
3509             Op  : Node_Kind;
3510             Val : Node_Id;
3511
3512          begin
3513             --  First check if we are in decisive conditional
3514
3515             Get_Current_Value_Condition (N, Op, Val);
3516
3517             if Nkind (Val) = N_Null then
3518                if Op = N_Op_Eq then
3519                   return False;
3520                elsif Op = N_Op_Ne then
3521                   return True;
3522                end if;
3523             end if;
3524
3525             --  If OK to do replacement, test Is_Known_Non_Null flag
3526
3527             if OK_To_Do_Constant_Replacement (E) then
3528                return Is_Known_Non_Null (E);
3529
3530             --  Otherwise if not safe to do replacement, then say so
3531
3532             else
3533                return False;
3534             end if;
3535          end;
3536
3537       --  True if access attribute
3538
3539       elsif Nkind (N) = N_Attribute_Reference
3540         and then (Attribute_Name (N) = Name_Access
3541                     or else
3542                   Attribute_Name (N) = Name_Unchecked_Access
3543                     or else
3544                   Attribute_Name (N) = Name_Unrestricted_Access)
3545       then
3546          return True;
3547
3548       --  True if allocator
3549
3550       elsif Nkind (N) = N_Allocator then
3551          return True;
3552
3553       --  For a conversion, true if expression is known non-null
3554
3555       elsif Nkind (N) = N_Type_Conversion then
3556          return Known_Non_Null (Expression (N));
3557
3558       --  Above are all cases where the value could be determined to be
3559       --  non-null. In all other cases, we don't know, so return False.
3560
3561       else
3562          return False;
3563       end if;
3564    end Known_Non_Null;
3565
3566    ----------------
3567    -- Known_Null --
3568    ----------------
3569
3570    function Known_Null (N : Node_Id) return Boolean is
3571    begin
3572       --  Checks for case where N is an entity reference
3573
3574       if Is_Entity_Name (N) and then Present (Entity (N)) then
3575          declare
3576             E   : constant Entity_Id := Entity (N);
3577             Op  : Node_Kind;
3578             Val : Node_Id;
3579
3580          begin
3581             --  First check if we are in decisive conditional
3582
3583             Get_Current_Value_Condition (N, Op, Val);
3584
3585             if Nkind (Val) = N_Null then
3586                if Op = N_Op_Eq then
3587                   return True;
3588                elsif Op = N_Op_Ne then
3589                   return False;
3590                end if;
3591             end if;
3592
3593             --  If OK to do replacement, test Is_Known_Null flag
3594
3595             if OK_To_Do_Constant_Replacement (E) then
3596                return Is_Known_Null (E);
3597
3598             --  Otherwise if not safe to do replacement, then say so
3599
3600             else
3601                return False;
3602             end if;
3603          end;
3604
3605       --  True if explicit reference to null
3606
3607       elsif Nkind (N) = N_Null then
3608          return True;
3609
3610       --  For a conversion, true if expression is known null
3611
3612       elsif Nkind (N) = N_Type_Conversion then
3613          return Known_Null (Expression (N));
3614
3615       --  Above are all cases where the value could be determined to be null.
3616       --  In all other cases, we don't know, so return False.
3617
3618       else
3619          return False;
3620       end if;
3621    end Known_Null;
3622
3623    -----------------------------
3624    -- Make_CW_Equivalent_Type --
3625    -----------------------------
3626
3627    --  Create a record type used as an equivalent of any member
3628    --  of the class which takes its size from exp.
3629
3630    --  Generate the following code:
3631
3632    --   type Equiv_T is record
3633    --     _parent :  T (List of discriminant constaints taken from Exp);
3634    --     Ext__50 : Storage_Array (1 .. (Exp'size - Typ'object_size)/8);
3635    --   end Equiv_T;
3636    --
3637    --   ??? Note that this type does not guarantee same alignment as all
3638    --   derived types
3639
3640    function Make_CW_Equivalent_Type
3641      (T : Entity_Id;
3642       E : Node_Id) return Entity_Id
3643    is
3644       Loc         : constant Source_Ptr := Sloc (E);
3645       Root_Typ    : constant Entity_Id  := Root_Type (T);
3646       List_Def    : constant List_Id    := Empty_List;
3647       Equiv_Type  : Entity_Id;
3648       Range_Type  : Entity_Id;
3649       Str_Type    : Entity_Id;
3650       Constr_Root : Entity_Id;
3651       Sizexpr     : Node_Id;
3652
3653    begin
3654       if not Has_Discriminants (Root_Typ) then
3655          Constr_Root := Root_Typ;
3656       else
3657          Constr_Root :=
3658            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
3659
3660          --  subtype cstr__n is T (List of discr constraints taken from Exp)
3661
3662          Append_To (List_Def,
3663            Make_Subtype_Declaration (Loc,
3664              Defining_Identifier => Constr_Root,
3665                Subtype_Indication =>
3666                  Make_Subtype_From_Expr (E, Root_Typ)));
3667       end if;
3668
3669       --  subtype rg__xx is Storage_Offset range
3670       --                           (Expr'size - typ'size) / Storage_Unit
3671
3672       Range_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('G'));
3673
3674       Sizexpr :=
3675         Make_Op_Subtract (Loc,
3676           Left_Opnd =>
3677             Make_Attribute_Reference (Loc,
3678               Prefix =>
3679                 OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)),
3680               Attribute_Name => Name_Size),
3681           Right_Opnd =>
3682             Make_Attribute_Reference (Loc,
3683               Prefix => New_Reference_To (Constr_Root, Loc),
3684               Attribute_Name => Name_Object_Size));
3685
3686       Set_Paren_Count (Sizexpr, 1);
3687
3688       Append_To (List_Def,
3689         Make_Subtype_Declaration (Loc,
3690           Defining_Identifier => Range_Type,
3691           Subtype_Indication =>
3692             Make_Subtype_Indication (Loc,
3693               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Offset), Loc),
3694               Constraint => Make_Range_Constraint (Loc,
3695                 Range_Expression =>
3696                   Make_Range (Loc,
3697                     Low_Bound => Make_Integer_Literal (Loc, 1),
3698                     High_Bound =>
3699                       Make_Op_Divide (Loc,
3700                         Left_Opnd => Sizexpr,
3701                         Right_Opnd => Make_Integer_Literal (Loc,
3702                             Intval => System_Storage_Unit)))))));
3703
3704       --  subtype str__nn is Storage_Array (rg__x);
3705
3706       Str_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('S'));
3707       Append_To (List_Def,
3708         Make_Subtype_Declaration (Loc,
3709           Defining_Identifier => Str_Type,
3710           Subtype_Indication =>
3711             Make_Subtype_Indication (Loc,
3712               Subtype_Mark => New_Reference_To (RTE (RE_Storage_Array), Loc),
3713               Constraint =>
3714                 Make_Index_Or_Discriminant_Constraint (Loc,
3715                   Constraints =>
3716                     New_List (New_Reference_To (Range_Type, Loc))))));
3717
3718       --  type Equiv_T is record
3719       --    _parent : Tnn;
3720       --    E : Str_Type;
3721       --  end Equiv_T;
3722
3723       Equiv_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
3724
3725       --  When the target requires front-end layout, it's necessary to allow
3726       --  the equivalent type to be frozen so that layout can occur (when the
3727       --  associated class-wide subtype is frozen, the equivalent type will
3728       --  be frozen, see freeze.adb). For other targets, Gigi wants to have
3729       --  the equivalent type marked as frozen and deals with this type itself.
3730       --  In the Gigi case this will also avoid the generation of an init
3731       --  procedure for the type.
3732
3733       if not Frontend_Layout_On_Target then
3734          Set_Is_Frozen (Equiv_Type);
3735       end if;
3736
3737       Set_Ekind (Equiv_Type, E_Record_Type);
3738       Set_Parent_Subtype (Equiv_Type, Constr_Root);
3739
3740       Append_To (List_Def,
3741         Make_Full_Type_Declaration (Loc,
3742           Defining_Identifier => Equiv_Type,
3743
3744           Type_Definition =>
3745             Make_Record_Definition (Loc,
3746               Component_List => Make_Component_List (Loc,
3747                 Component_Items => New_List (
3748                   Make_Component_Declaration (Loc,
3749                     Defining_Identifier =>
3750                       Make_Defining_Identifier (Loc, Name_uParent),
3751                     Component_Definition =>
3752                       Make_Component_Definition (Loc,
3753                         Aliased_Present    => False,
3754                         Subtype_Indication =>
3755                           New_Reference_To (Constr_Root, Loc))),
3756
3757                   Make_Component_Declaration (Loc,
3758                     Defining_Identifier =>
3759                       Make_Defining_Identifier (Loc,
3760                         Chars => New_Internal_Name ('C')),
3761                     Component_Definition =>
3762                       Make_Component_Definition (Loc,
3763                         Aliased_Present    => False,
3764                         Subtype_Indication =>
3765                           New_Reference_To (Str_Type, Loc)))),
3766
3767                 Variant_Part => Empty))));
3768
3769       Insert_Actions (E, List_Def);
3770       return Equiv_Type;
3771    end Make_CW_Equivalent_Type;
3772
3773    ------------------------
3774    -- Make_Literal_Range --
3775    ------------------------
3776
3777    function Make_Literal_Range
3778      (Loc         : Source_Ptr;
3779       Literal_Typ : Entity_Id) return Node_Id
3780    is
3781       Lo : constant Node_Id :=
3782              New_Copy_Tree (String_Literal_Low_Bound (Literal_Typ));
3783
3784    begin
3785       Set_Analyzed (Lo, False);
3786
3787          return
3788            Make_Range (Loc,
3789              Low_Bound => Lo,
3790
3791              High_Bound =>
3792                Make_Op_Subtract (Loc,
3793                   Left_Opnd =>
3794                     Make_Op_Add (Loc,
3795                       Left_Opnd  => New_Copy_Tree (Lo),
3796                       Right_Opnd =>
3797                         Make_Integer_Literal (Loc,
3798                           String_Literal_Length (Literal_Typ))),
3799                   Right_Opnd => Make_Integer_Literal (Loc, 1)));
3800    end Make_Literal_Range;
3801
3802    ----------------------------
3803    -- Make_Subtype_From_Expr --
3804    ----------------------------
3805
3806    --  1. If Expr is an uncontrained array expression, creates
3807    --    Unc_Type(Expr'first(1)..Expr'Last(1),..., Expr'first(n)..Expr'last(n))
3808
3809    --  2. If Expr is a unconstrained discriminated type expression, creates
3810    --    Unc_Type(Expr.Discr1, ... , Expr.Discr_n)
3811
3812    --  3. If Expr is class-wide, creates an implicit class wide subtype
3813
3814    function Make_Subtype_From_Expr
3815      (E       : Node_Id;
3816       Unc_Typ : Entity_Id) return Node_Id
3817    is
3818       Loc         : constant Source_Ptr := Sloc (E);
3819       List_Constr : constant List_Id    := New_List;
3820       D           : Entity_Id;
3821
3822       Full_Subtyp  : Entity_Id;
3823       Priv_Subtyp  : Entity_Id;
3824       Utyp         : Entity_Id;
3825       Full_Exp     : Node_Id;
3826
3827    begin
3828       if Is_Private_Type (Unc_Typ)
3829         and then Has_Unknown_Discriminants (Unc_Typ)
3830       then
3831          --  Prepare the subtype completion, Go to base type to
3832          --  find underlying type, because the type may be a generic
3833          --  actual or an explicit subtype.
3834
3835          Utyp        := Underlying_Type (Base_Type (Unc_Typ));
3836          Full_Subtyp := Make_Defining_Identifier (Loc,
3837                           New_Internal_Name ('C'));
3838          Full_Exp    :=
3839            Unchecked_Convert_To
3840              (Utyp, Duplicate_Subexpr_No_Checks (E));
3841          Set_Parent (Full_Exp, Parent (E));
3842
3843          Priv_Subtyp :=
3844            Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
3845
3846          Insert_Action (E,
3847            Make_Subtype_Declaration (Loc,
3848              Defining_Identifier => Full_Subtyp,
3849              Subtype_Indication  => Make_Subtype_From_Expr (Full_Exp, Utyp)));
3850
3851          --  Define the dummy private subtype
3852
3853          Set_Ekind          (Priv_Subtyp, Subtype_Kind (Ekind (Unc_Typ)));
3854          Set_Etype          (Priv_Subtyp, Base_Type (Unc_Typ));
3855          Set_Scope          (Priv_Subtyp, Full_Subtyp);
3856          Set_Is_Constrained (Priv_Subtyp);
3857          Set_Is_Tagged_Type (Priv_Subtyp, Is_Tagged_Type (Unc_Typ));
3858          Set_Is_Itype       (Priv_Subtyp);
3859          Set_Associated_Node_For_Itype (Priv_Subtyp, E);
3860
3861          if Is_Tagged_Type  (Priv_Subtyp) then
3862             Set_Class_Wide_Type
3863               (Base_Type (Priv_Subtyp), Class_Wide_Type (Unc_Typ));
3864             Set_Primitive_Operations (Priv_Subtyp,
3865               Primitive_Operations (Unc_Typ));
3866          end if;
3867
3868          Set_Full_View (Priv_Subtyp, Full_Subtyp);
3869
3870          return New_Reference_To (Priv_Subtyp, Loc);
3871
3872       elsif Is_Array_Type (Unc_Typ) then
3873          for J in 1 .. Number_Dimensions (Unc_Typ) loop
3874             Append_To (List_Constr,
3875               Make_Range (Loc,
3876                 Low_Bound =>
3877                   Make_Attribute_Reference (Loc,
3878                     Prefix => Duplicate_Subexpr_No_Checks (E),
3879                     Attribute_Name => Name_First,
3880                     Expressions => New_List (
3881                       Make_Integer_Literal (Loc, J))),
3882
3883                 High_Bound =>
3884                   Make_Attribute_Reference (Loc,
3885                     Prefix         => Duplicate_Subexpr_No_Checks (E),
3886                     Attribute_Name => Name_Last,
3887                     Expressions    => New_List (
3888                       Make_Integer_Literal (Loc, J)))));
3889          end loop;
3890
3891       elsif Is_Class_Wide_Type (Unc_Typ) then
3892          declare
3893             CW_Subtype : Entity_Id;
3894             EQ_Typ     : Entity_Id := Empty;
3895
3896          begin
3897             --  A class-wide equivalent type is not needed when Java_VM
3898             --  because the JVM back end handles the class-wide object
3899             --  initialization itself (and doesn't need or want the
3900             --  additional intermediate type to handle the assignment).
3901
3902             if Expander_Active and then not Java_VM then
3903                EQ_Typ := Make_CW_Equivalent_Type (Unc_Typ, E);
3904             end if;
3905
3906             CW_Subtype := New_Class_Wide_Subtype (Unc_Typ, E);
3907             Set_Equivalent_Type (CW_Subtype, EQ_Typ);
3908
3909             if Present (EQ_Typ) then
3910                Set_Is_Class_Wide_Equivalent_Type (EQ_Typ);
3911             end if;
3912
3913             Set_Cloned_Subtype (CW_Subtype, Base_Type (Unc_Typ));
3914
3915             return New_Occurrence_Of (CW_Subtype, Loc);
3916          end;
3917
3918       --  Indefinite record type with discriminants
3919
3920       else
3921          D := First_Discriminant (Unc_Typ);
3922          while Present (D) loop
3923             Append_To (List_Constr,
3924               Make_Selected_Component (Loc,
3925                 Prefix        => Duplicate_Subexpr_No_Checks (E),
3926                 Selector_Name => New_Reference_To (D, Loc)));
3927
3928             Next_Discriminant (D);
3929          end loop;
3930       end if;
3931
3932       return
3933         Make_Subtype_Indication (Loc,
3934           Subtype_Mark => New_Reference_To (Unc_Typ, Loc),
3935           Constraint   =>
3936             Make_Index_Or_Discriminant_Constraint (Loc,
3937               Constraints => List_Constr));
3938    end Make_Subtype_From_Expr;
3939
3940    -----------------------------
3941    -- May_Generate_Large_Temp --
3942    -----------------------------
3943
3944    --  At the current time, the only types that we return False for (i.e.
3945    --  where we decide we know they cannot generate large temps) are ones
3946    --  where we know the size is 256 bits or less at compile time, and we
3947    --  are still not doing a thorough job on arrays and records ???
3948
3949    function May_Generate_Large_Temp (Typ : Entity_Id) return Boolean is
3950    begin
3951       if not Size_Known_At_Compile_Time (Typ) then
3952          return False;
3953
3954       elsif Esize (Typ) /= 0 and then Esize (Typ) <= 256 then
3955          return False;
3956
3957       elsif Is_Array_Type (Typ)
3958         and then Present (Packed_Array_Type (Typ))
3959       then
3960          return May_Generate_Large_Temp (Packed_Array_Type (Typ));
3961
3962       --  We could do more here to find other small types ???
3963
3964       else
3965          return True;
3966       end if;
3967    end May_Generate_Large_Temp;
3968
3969    ----------------------------
3970    -- New_Class_Wide_Subtype --
3971    ----------------------------
3972
3973    function New_Class_Wide_Subtype
3974      (CW_Typ : Entity_Id;
3975       N      : Node_Id) return Entity_Id
3976    is
3977       Res       : constant Entity_Id := Create_Itype (E_Void, N);
3978       Res_Name  : constant Name_Id   := Chars (Res);
3979       Res_Scope : constant Entity_Id := Scope (Res);
3980
3981    begin
3982       Copy_Node (CW_Typ, Res);
3983       Set_Comes_From_Source (Res, False);
3984       Set_Sloc (Res, Sloc (N));
3985       Set_Is_Itype (Res);
3986       Set_Associated_Node_For_Itype (Res, N);
3987       Set_Is_Public (Res, False);   --  By default, may be changed below.
3988       Set_Public_Status (Res);
3989       Set_Chars (Res, Res_Name);
3990       Set_Scope (Res, Res_Scope);
3991       Set_Ekind (Res, E_Class_Wide_Subtype);
3992       Set_Next_Entity (Res, Empty);
3993       Set_Etype (Res, Base_Type (CW_Typ));
3994
3995       --  For targets where front-end layout is required, reset the Is_Frozen
3996       --  status of the subtype to False (it can be implicitly set to true
3997       --  from the copy of the class-wide type). For other targets, Gigi
3998       --  doesn't want the class-wide subtype to go through the freezing
3999       --  process (though it's unclear why that causes problems and it would
4000       --  be nice to allow freezing to occur normally for all targets ???).
4001
4002       if Frontend_Layout_On_Target then
4003          Set_Is_Frozen (Res, False);
4004       end if;
4005
4006       Set_Freeze_Node (Res, Empty);
4007       return (Res);
4008    end New_Class_Wide_Subtype;
4009
4010    -----------------------------------
4011    -- OK_To_Do_Constant_Replacement --
4012    -----------------------------------
4013
4014    function OK_To_Do_Constant_Replacement (E : Entity_Id) return Boolean is
4015       ES : constant Entity_Id := Scope (E);
4016       CS : Entity_Id;
4017
4018    begin
4019       --  Do not replace statically allocated objects, because they may be
4020       --  modified outside the current scope.
4021
4022       if Is_Statically_Allocated (E) then
4023          return False;
4024
4025       --  Do not replace aliased or volatile objects, since we don't know what
4026       --  else might change the value.
4027
4028       elsif Is_Aliased (E) or else Treat_As_Volatile (E) then
4029          return False;
4030
4031       --  Debug flag -gnatdM disconnects this optimization
4032
4033       elsif Debug_Flag_MM then
4034          return False;
4035
4036       --  Otherwise check scopes
4037
4038       else
4039          CS := Current_Scope;
4040
4041          loop
4042             --  If we are in right scope, replacement is safe
4043
4044             if CS = ES then
4045                return True;
4046
4047             --  Packages do not affect the determination of safety
4048
4049             elsif Ekind (CS) = E_Package then
4050                exit when CS = Standard_Standard;
4051                CS := Scope (CS);
4052
4053             --  Blocks do not affect the determination of safety
4054
4055             elsif Ekind (CS) = E_Block then
4056                CS := Scope (CS);
4057
4058             --  Loops do not affect the determination of safety. Note that we
4059             --  kill all current values on entry to a loop, so we are just
4060             --  talking about processing within a loop here.
4061
4062             elsif Ekind (CS) = E_Loop then
4063                CS := Scope (CS);
4064
4065             --  Otherwise, the reference is dubious, and we cannot be sure that
4066             --  it is safe to do the replacement.
4067
4068             else
4069                exit;
4070             end if;
4071          end loop;
4072
4073          return False;
4074       end if;
4075    end OK_To_Do_Constant_Replacement;
4076
4077    -------------------------
4078    -- Remove_Side_Effects --
4079    -------------------------
4080
4081    procedure Remove_Side_Effects
4082      (Exp          : Node_Id;
4083       Name_Req     : Boolean := False;
4084       Variable_Ref : Boolean := False)
4085    is
4086       Loc          : constant Source_Ptr     := Sloc (Exp);
4087       Exp_Type     : constant Entity_Id      := Etype (Exp);
4088       Svg_Suppress : constant Suppress_Array := Scope_Suppress;
4089       Def_Id       : Entity_Id;
4090       Ref_Type     : Entity_Id;
4091       Res          : Node_Id;
4092       Ptr_Typ_Decl : Node_Id;
4093       New_Exp      : Node_Id;
4094       E            : Node_Id;
4095
4096       function Side_Effect_Free (N : Node_Id) return Boolean;
4097       --  Determines if the tree N represents an expression that is known not
4098       --  to have side effects, and for which no processing is required.
4099
4100       function Side_Effect_Free (L : List_Id) return Boolean;
4101       --  Determines if all elements of the list L are side effect free
4102
4103       function Safe_Prefixed_Reference (N : Node_Id) return Boolean;
4104       --  The argument N is a construct where the Prefix is dereferenced if it
4105       --  is an access type and the result is a variable. The call returns True
4106       --  if the construct is side effect free (not considering side effects in
4107       --  other than the prefix which are to be tested by the caller).
4108
4109       function Within_In_Parameter (N : Node_Id) return Boolean;
4110       --  Determines if N is a subcomponent of a composite in-parameter. If so,
4111       --  N is not side-effect free when the actual is global and modifiable
4112       --  indirectly from within a subprogram, because it may be passed by
4113       --  reference. The front-end must be conservative here and assume that
4114       --  this may happen with any array or record type. On the other hand, we
4115       --  cannot create temporaries for all expressions for which this
4116       --  condition is true, for various reasons that might require clearing up
4117       --  ??? For example, descriminant references that appear out of place, or
4118       --  spurious type errors with class-wide expressions. As a result, we
4119       --  limit the transformation to loop bounds, which is so far the only
4120       --  case that requires it.
4121
4122       -----------------------------
4123       -- Safe_Prefixed_Reference --
4124       -----------------------------
4125
4126       function Safe_Prefixed_Reference (N : Node_Id) return Boolean is
4127       begin
4128          --  If prefix is not side effect free, definitely not safe
4129
4130          if not Side_Effect_Free (Prefix (N)) then
4131             return False;
4132
4133          --  If the prefix is of an access type that is not access-to-constant,
4134          --  then this construct is a variable reference, which means it is to
4135          --  be considered to have side effects if Variable_Ref is set True
4136          --  Exception is an access to an entity that is a constant or an
4137          --  in-parameter which does not come from source, and is the result
4138          --  of a previous removal of side-effects.
4139
4140          elsif Is_Access_Type (Etype (Prefix (N)))
4141            and then not Is_Access_Constant (Etype (Prefix (N)))
4142            and then Variable_Ref
4143          then
4144             if not Is_Entity_Name (Prefix (N)) then
4145                return False;
4146             else
4147                return Ekind (Entity (Prefix (N))) = E_Constant
4148                  or else Ekind (Entity (Prefix (N))) = E_In_Parameter;
4149             end if;
4150
4151          --  The following test is the simplest way of solving a complex
4152          --  problem uncovered by BB08-010: Side effect on loop bound that
4153          --  is a subcomponent of a global variable:
4154          --    If a loop bound is a subcomponent of a global variable, a
4155          --    modification of that variable within the loop may incorrectly
4156          --    affect the execution of the loop.
4157
4158          elsif not
4159            (Nkind (Parent (Parent (N))) /= N_Loop_Parameter_Specification
4160               or else not Within_In_Parameter (Prefix (N)))
4161          then
4162             return False;
4163
4164          --  All other cases are side effect free
4165
4166          else
4167             return True;
4168          end if;
4169       end Safe_Prefixed_Reference;
4170
4171       ----------------------
4172       -- Side_Effect_Free --
4173       ----------------------
4174
4175       function Side_Effect_Free (N : Node_Id) return Boolean is
4176       begin
4177          --  Note on checks that could raise Constraint_Error. Strictly, if
4178          --  we take advantage of 11.6, these checks do not count as side
4179          --  effects. However, we would just as soon consider that they are
4180          --  side effects, since the backend CSE does not work very well on
4181          --  expressions which can raise Constraint_Error. On the other
4182          --  hand, if we do not consider them to be side effect free, then
4183          --  we get some awkward expansions in -gnato mode, resulting in
4184          --  code insertions at a point where we do not have a clear model
4185          --  for performing the insertions. See 4908-002/comment for details.
4186
4187          --  Special handling for entity names
4188
4189          if Is_Entity_Name (N) then
4190
4191             --  If the entity is a constant, it is definitely side effect
4192             --  free. Note that the test of Is_Variable (N) below might
4193             --  be expected to catch this case, but it does not, because
4194             --  this test goes to the original tree, and we may have
4195             --  already rewritten a variable node with a constant as
4196             --  a result of an earlier Force_Evaluation call.
4197
4198             if Ekind (Entity (N)) = E_Constant
4199               or else Ekind (Entity (N)) = E_In_Parameter
4200             then
4201                return True;
4202
4203             --  Functions are not side effect free
4204
4205             elsif Ekind (Entity (N)) = E_Function then
4206                return False;
4207
4208             --  Variables are considered to be a side effect if Variable_Ref
4209             --  is set or if we have a volatile variable and Name_Req is off.
4210             --  If Name_Req is True then we can't help returning a name which
4211             --  effectively allows multiple references in any case.
4212
4213             elsif Is_Variable (N) then
4214                return not Variable_Ref
4215                  and then (not Treat_As_Volatile (Entity (N))
4216                              or else Name_Req);
4217
4218             --  Any other entity (e.g. a subtype name) is definitely side
4219             --  effect free.
4220
4221             else
4222                return True;
4223             end if;
4224
4225          --  A value known at compile time is always side effect free
4226
4227          elsif Compile_Time_Known_Value (N) then
4228             return True;
4229          end if;
4230
4231          --  For other than entity names and compile time known values,
4232          --  check the node kind for special processing.
4233
4234          case Nkind (N) is
4235
4236             --  An attribute reference is side effect free if its expressions
4237             --  are side effect free and its prefix is side effect free or
4238             --  is an entity reference.
4239
4240             --  Is this right? what about x'first where x is a variable???
4241
4242             when N_Attribute_Reference =>
4243                return Side_Effect_Free (Expressions (N))
4244                  and then Attribute_Name (N) /= Name_Input
4245                  and then (Is_Entity_Name (Prefix (N))
4246                             or else Side_Effect_Free (Prefix (N)));
4247
4248             --  A binary operator is side effect free if and both operands
4249             --  are side effect free. For this purpose binary operators
4250             --  include membership tests and short circuit forms
4251
4252             when N_Binary_Op       |
4253                  N_Membership_Test |
4254                  N_And_Then        |
4255                  N_Or_Else         =>
4256                return Side_Effect_Free (Left_Opnd  (N))
4257                  and then Side_Effect_Free (Right_Opnd (N));
4258
4259             --  An explicit dereference is side effect free only if it is
4260             --  a side effect free prefixed reference.
4261
4262             when N_Explicit_Dereference =>
4263                return Safe_Prefixed_Reference (N);
4264
4265             --  A call to _rep_to_pos is side effect free, since we generate
4266             --  this pure function call ourselves. Moreover it is critically
4267             --  important to make this exception, since otherwise we can
4268             --  have discriminants in array components which don't look
4269             --  side effect free in the case of an array whose index type
4270             --  is an enumeration type with an enumeration rep clause.
4271
4272             --  All other function calls are not side effect free
4273
4274             when N_Function_Call =>
4275                return Nkind (Name (N)) = N_Identifier
4276                  and then Is_TSS (Name (N), TSS_Rep_To_Pos)
4277                  and then
4278                    Side_Effect_Free (First (Parameter_Associations (N)));
4279
4280             --  An indexed component is side effect free if it is a side
4281             --  effect free prefixed reference and all the indexing
4282             --  expressions are side effect free.
4283
4284             when N_Indexed_Component =>
4285                return Side_Effect_Free (Expressions (N))
4286                  and then Safe_Prefixed_Reference (N);
4287
4288             --  A type qualification is side effect free if the expression
4289             --  is side effect free.
4290
4291             when N_Qualified_Expression =>
4292                return Side_Effect_Free (Expression (N));
4293
4294             --  A selected component is side effect free only if it is a
4295             --  side effect free prefixed reference.
4296
4297             when N_Selected_Component =>
4298                return Safe_Prefixed_Reference (N);
4299
4300             --  A range is side effect free if the bounds are side effect free
4301
4302             when N_Range =>
4303                return Side_Effect_Free (Low_Bound (N))
4304                  and then Side_Effect_Free (High_Bound (N));
4305
4306             --  A slice is side effect free if it is a side effect free
4307             --  prefixed reference and the bounds are side effect free.
4308
4309             when N_Slice =>
4310                return Side_Effect_Free (Discrete_Range (N))
4311                  and then Safe_Prefixed_Reference (N);
4312
4313             --  A type conversion is side effect free if the expression
4314             --  to be converted is side effect free.
4315
4316             when N_Type_Conversion =>
4317                return Side_Effect_Free (Expression (N));
4318
4319             --  A unary operator is side effect free if the operand
4320             --  is side effect free.
4321
4322             when N_Unary_Op =>
4323                return Side_Effect_Free (Right_Opnd (N));
4324
4325             --  An unchecked type conversion is side effect free only if it
4326             --  is safe and its argument is side effect free.
4327
4328             when N_Unchecked_Type_Conversion =>
4329                return Safe_Unchecked_Type_Conversion (N)
4330                  and then Side_Effect_Free (Expression (N));
4331
4332             --  An unchecked expression is side effect free if its expression
4333             --  is side effect free.
4334
4335             when N_Unchecked_Expression =>
4336                return Side_Effect_Free (Expression (N));
4337
4338             --  A literal is side effect free
4339
4340             when N_Character_Literal    |
4341                  N_Integer_Literal      |
4342                  N_Real_Literal         |
4343                  N_String_Literal       =>
4344                return True;
4345
4346             --  We consider that anything else has side effects. This is a bit
4347             --  crude, but we are pretty close for most common cases, and we
4348             --  are certainly correct (i.e. we never return True when the
4349             --  answer should be False).
4350
4351             when others =>
4352                return False;
4353          end case;
4354       end Side_Effect_Free;
4355
4356       --  A list is side effect free if all elements of the list are
4357       --  side effect free.
4358
4359       function Side_Effect_Free (L : List_Id) return Boolean is
4360          N : Node_Id;
4361
4362       begin
4363          if L = No_List or else L = Error_List then
4364             return True;
4365
4366          else
4367             N := First (L);
4368             while Present (N) loop
4369                if not Side_Effect_Free (N) then
4370                   return False;
4371                else
4372                   Next (N);
4373                end if;
4374             end loop;
4375
4376             return True;
4377          end if;
4378       end Side_Effect_Free;
4379
4380       -------------------------
4381       -- Within_In_Parameter --
4382       -------------------------
4383
4384       function Within_In_Parameter (N : Node_Id) return Boolean is
4385       begin
4386          if not Comes_From_Source (N) then
4387             return False;
4388
4389          elsif Is_Entity_Name (N) then
4390             return
4391               Ekind (Entity (N)) = E_In_Parameter;
4392
4393          elsif Nkind (N) = N_Indexed_Component
4394            or else Nkind (N) = N_Selected_Component
4395          then
4396             return Within_In_Parameter (Prefix (N));
4397          else
4398
4399             return False;
4400          end if;
4401       end Within_In_Parameter;
4402
4403    --  Start of processing for Remove_Side_Effects
4404
4405    begin
4406       --  If we are side effect free already or expansion is disabled,
4407       --  there is nothing to do.
4408
4409       if Side_Effect_Free (Exp) or else not Expander_Active then
4410          return;
4411       end if;
4412
4413       --  All this must not have any checks
4414
4415       Scope_Suppress := (others => True);
4416
4417       --  If it is a scalar type and we need to capture the value, just
4418       --  make a copy.  Likewise for a function call.  And if we have a
4419       --  volatile variable and Nam_Req is not set (see comments above
4420       --  for Side_Effect_Free).
4421
4422       if Is_Elementary_Type (Exp_Type)
4423         and then (Variable_Ref
4424                    or else Nkind (Exp) = N_Function_Call
4425                    or else (not Name_Req
4426                              and then Is_Entity_Name (Exp)
4427                              and then Treat_As_Volatile (Entity (Exp))))
4428       then
4429
4430          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4431          Set_Etype (Def_Id, Exp_Type);
4432          Res := New_Reference_To (Def_Id, Loc);
4433
4434          E :=
4435            Make_Object_Declaration (Loc,
4436              Defining_Identifier => Def_Id,
4437              Object_Definition   => New_Reference_To (Exp_Type, Loc),
4438              Constant_Present    => True,
4439              Expression          => Relocate_Node (Exp));
4440
4441          Set_Assignment_OK (E);
4442          Insert_Action (Exp, E);
4443
4444       --  If the expression has the form v.all then we can just capture
4445       --  the pointer, and then do an explicit dereference on the result.
4446
4447       elsif Nkind (Exp) = N_Explicit_Dereference then
4448          Def_Id :=
4449            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4450          Res :=
4451            Make_Explicit_Dereference (Loc, New_Reference_To (Def_Id, Loc));
4452
4453          Insert_Action (Exp,
4454            Make_Object_Declaration (Loc,
4455              Defining_Identifier => Def_Id,
4456              Object_Definition   =>
4457                New_Reference_To (Etype (Prefix (Exp)), Loc),
4458              Constant_Present    => True,
4459              Expression          => Relocate_Node (Prefix (Exp))));
4460
4461       --  Similar processing for an unchecked conversion of an expression
4462       --  of the form v.all, where we want the same kind of treatment.
4463
4464       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4465         and then Nkind (Expression (Exp)) = N_Explicit_Dereference
4466       then
4467          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4468          Scope_Suppress := Svg_Suppress;
4469          return;
4470
4471       --  If this is a type conversion, leave the type conversion and remove
4472       --  the side effects in the expression. This is important in several
4473       --  circumstances: for change of representations, and also when this
4474       --  is a view conversion to a smaller object, where gigi can end up
4475       --  creating its own temporary of the wrong size.
4476
4477       elsif Nkind (Exp) = N_Type_Conversion then
4478          Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref);
4479          Scope_Suppress := Svg_Suppress;
4480          return;
4481
4482       --  If this is an unchecked conversion that Gigi can't handle, make
4483       --  a copy or a use a renaming to capture the value.
4484
4485       elsif Nkind (Exp) = N_Unchecked_Type_Conversion
4486         and then not Safe_Unchecked_Type_Conversion (Exp)
4487       then
4488          if Controlled_Type (Exp_Type) then
4489
4490             --  Use a renaming to capture the expression, rather than create
4491             --  a controlled temporary.
4492
4493             Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4494             Res := New_Reference_To (Def_Id, Loc);
4495
4496             Insert_Action (Exp,
4497               Make_Object_Renaming_Declaration (Loc,
4498                 Defining_Identifier => Def_Id,
4499                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4500                 Name                => Relocate_Node (Exp)));
4501
4502          else
4503             Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4504             Set_Etype (Def_Id, Exp_Type);
4505             Res := New_Reference_To (Def_Id, Loc);
4506
4507             E :=
4508               Make_Object_Declaration (Loc,
4509                 Defining_Identifier => Def_Id,
4510                 Object_Definition   => New_Reference_To (Exp_Type, Loc),
4511                 Constant_Present    => not Is_Variable (Exp),
4512                 Expression          => Relocate_Node (Exp));
4513
4514             Set_Assignment_OK (E);
4515             Insert_Action (Exp, E);
4516          end if;
4517
4518       --  For expressions that denote objects, we can use a renaming scheme.
4519       --  We skip using this if we have a volatile variable and we do not
4520       --  have Nam_Req set true (see comments above for Side_Effect_Free).
4521
4522       elsif Is_Object_Reference (Exp)
4523         and then Nkind (Exp) /= N_Function_Call
4524         and then (Name_Req
4525                    or else not Is_Entity_Name (Exp)
4526                    or else not Treat_As_Volatile (Entity (Exp)))
4527       then
4528          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4529
4530          if Nkind (Exp) = N_Selected_Component
4531            and then Nkind (Prefix (Exp)) = N_Function_Call
4532            and then Is_Array_Type (Exp_Type)
4533          then
4534             --  Avoid generating a variable-sized temporary, by generating
4535             --  the renaming declaration just for the function call. The
4536             --  transformation could be refined to apply only when the array
4537             --  component is constrained by a discriminant???
4538
4539             Res :=
4540               Make_Selected_Component (Loc,
4541                 Prefix => New_Occurrence_Of (Def_Id, Loc),
4542                 Selector_Name => Selector_Name (Exp));
4543
4544             Insert_Action (Exp,
4545               Make_Object_Renaming_Declaration (Loc,
4546                 Defining_Identifier => Def_Id,
4547                 Subtype_Mark        =>
4548                   New_Reference_To (Base_Type (Etype (Prefix (Exp))), Loc),
4549                 Name                => Relocate_Node (Prefix (Exp))));
4550
4551          else
4552             Res := New_Reference_To (Def_Id, Loc);
4553
4554             Insert_Action (Exp,
4555               Make_Object_Renaming_Declaration (Loc,
4556                 Defining_Identifier => Def_Id,
4557                 Subtype_Mark        => New_Reference_To (Exp_Type, Loc),
4558                 Name                => Relocate_Node (Exp)));
4559
4560          end if;
4561
4562          --  If this is a packed reference, or a selected component with a
4563          --  non-standard representation, a reference to the temporary will
4564          --  be replaced by a copy of the original expression (see
4565          --  exp_ch2.Expand_Renaming). Otherwise the temporary must be
4566          --  elaborated by gigi, and is of course not to be replaced in-line
4567          --  by the expression it renames, which would defeat the purpose of
4568          --  removing the side-effect.
4569
4570          if (Nkind (Exp) = N_Selected_Component
4571               or else Nkind (Exp) = N_Indexed_Component)
4572            and then Has_Non_Standard_Rep (Etype (Prefix (Exp)))
4573          then
4574             null;
4575          else
4576             Set_Is_Renaming_Of_Object (Def_Id, False);
4577          end if;
4578
4579       --  Otherwise we generate a reference to the value
4580
4581       else
4582          Ref_Type := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4583
4584          Ptr_Typ_Decl :=
4585            Make_Full_Type_Declaration (Loc,
4586              Defining_Identifier => Ref_Type,
4587              Type_Definition =>
4588                Make_Access_To_Object_Definition (Loc,
4589                  All_Present => True,
4590                  Subtype_Indication =>
4591                    New_Reference_To (Exp_Type, Loc)));
4592
4593          E := Exp;
4594          Insert_Action (Exp, Ptr_Typ_Decl);
4595
4596          Def_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
4597          Set_Etype (Def_Id, Exp_Type);
4598
4599          Res :=
4600            Make_Explicit_Dereference (Loc,
4601              Prefix => New_Reference_To (Def_Id, Loc));
4602
4603          if Nkind (E) = N_Explicit_Dereference then
4604             New_Exp := Relocate_Node (Prefix (E));
4605          else
4606             E := Relocate_Node (E);
4607             New_Exp := Make_Reference (Loc, E);
4608          end if;
4609
4610          if Is_Delayed_Aggregate (E) then
4611
4612             --  The expansion of nested aggregates is delayed until the
4613             --  enclosing aggregate is expanded. As aggregates are often
4614             --  qualified, the predicate applies to qualified expressions
4615             --  as well, indicating that the enclosing aggregate has not
4616             --  been expanded yet. At this point the aggregate is part of
4617             --  a stand-alone declaration, and must be fully expanded.
4618
4619             if Nkind (E) = N_Qualified_Expression then
4620                Set_Expansion_Delayed (Expression (E), False);
4621                Set_Analyzed (Expression (E), False);
4622             else
4623                Set_Expansion_Delayed (E, False);
4624             end if;
4625
4626             Set_Analyzed (E, False);
4627          end if;
4628
4629          Insert_Action (Exp,
4630            Make_Object_Declaration (Loc,
4631              Defining_Identifier => Def_Id,
4632              Object_Definition   => New_Reference_To (Ref_Type, Loc),
4633              Expression          => New_Exp));
4634       end if;
4635
4636       --  Preserve the Assignment_OK flag in all copies, since at least
4637       --  one copy may be used in a context where this flag must be set
4638       --  (otherwise why would the flag be set in the first place).
4639
4640       Set_Assignment_OK (Res, Assignment_OK (Exp));
4641
4642       --  Finally rewrite the original expression and we are done
4643
4644       Rewrite (Exp, Res);
4645       Analyze_And_Resolve (Exp, Exp_Type);
4646       Scope_Suppress := Svg_Suppress;
4647    end Remove_Side_Effects;
4648
4649    ---------------------------
4650    -- Represented_As_Scalar --
4651    ---------------------------
4652
4653    function Represented_As_Scalar (T : Entity_Id) return Boolean is
4654       UT : constant Entity_Id := Underlying_Type (T);
4655    begin
4656       return Is_Scalar_Type (UT)
4657         or else (Is_Bit_Packed_Array (UT)
4658                    and then Is_Scalar_Type (Packed_Array_Type (UT)));
4659    end Represented_As_Scalar;
4660
4661    ------------------------------------
4662    -- Safe_Unchecked_Type_Conversion --
4663    ------------------------------------
4664
4665    --  Note: this function knows quite a bit about the exact requirements
4666    --  of Gigi with respect to unchecked type conversions, and its code
4667    --  must be coordinated with any changes in Gigi in this area.
4668
4669    --  The above requirements should be documented in Sinfo ???
4670
4671    function Safe_Unchecked_Type_Conversion (Exp : Node_Id) return Boolean is
4672       Otyp   : Entity_Id;
4673       Ityp   : Entity_Id;
4674       Oalign : Uint;
4675       Ialign : Uint;
4676       Pexp   : constant Node_Id := Parent (Exp);
4677
4678    begin
4679       --  If the expression is the RHS of an assignment or object declaration
4680       --   we are always OK because there will always be a target.
4681
4682       --  Object renaming declarations, (generated for view conversions of
4683       --  actuals in inlined calls), like object declarations, provide an
4684       --  explicit type, and are safe as well.
4685
4686       if (Nkind (Pexp) = N_Assignment_Statement
4687            and then Expression (Pexp) = Exp)
4688         or else Nkind (Pexp) = N_Object_Declaration
4689         or else Nkind (Pexp) = N_Object_Renaming_Declaration
4690       then
4691          return True;
4692
4693       --  If the expression is the prefix of an N_Selected_Component
4694       --  we should also be OK because GCC knows to look inside the
4695       --  conversion except if the type is discriminated. We assume
4696       --  that we are OK anyway if the type is not set yet or if it is
4697       --  controlled since we can't afford to introduce a temporary in
4698       --  this case.
4699
4700       elsif Nkind (Pexp) = N_Selected_Component
4701          and then Prefix (Pexp) = Exp
4702       then
4703          if No (Etype (Pexp)) then
4704             return True;
4705          else
4706             return
4707               not Has_Discriminants (Etype (Pexp))
4708                 or else Is_Constrained (Etype (Pexp));
4709          end if;
4710       end if;
4711
4712       --  Set the output type, this comes from Etype if it is set, otherwise
4713       --  we take it from the subtype mark, which we assume was already
4714       --  fully analyzed.
4715
4716       if Present (Etype (Exp)) then
4717          Otyp := Etype (Exp);
4718       else
4719          Otyp := Entity (Subtype_Mark (Exp));
4720       end if;
4721
4722       --  The input type always comes from the expression, and we assume
4723       --  this is indeed always analyzed, so we can simply get the Etype.
4724
4725       Ityp := Etype (Expression (Exp));
4726
4727       --  Initialize alignments to unknown so far
4728
4729       Oalign := No_Uint;
4730       Ialign := No_Uint;
4731
4732       --  Replace a concurrent type by its corresponding record type
4733       --  and each type by its underlying type and do the tests on those.
4734       --  The original type may be a private type whose completion is a
4735       --  concurrent type, so find the underlying type first.
4736
4737       if Present (Underlying_Type (Otyp)) then
4738          Otyp := Underlying_Type (Otyp);
4739       end if;
4740
4741       if Present (Underlying_Type (Ityp)) then
4742          Ityp := Underlying_Type (Ityp);
4743       end if;
4744
4745       if Is_Concurrent_Type (Otyp) then
4746          Otyp := Corresponding_Record_Type (Otyp);
4747       end if;
4748
4749       if Is_Concurrent_Type (Ityp) then
4750          Ityp := Corresponding_Record_Type (Ityp);
4751       end if;
4752
4753       --  If the base types are the same, we know there is no problem since
4754       --  this conversion will be a noop.
4755
4756       if Implementation_Base_Type (Otyp) = Implementation_Base_Type (Ityp) then
4757          return True;
4758
4759       --  Same if this is an upwards conversion of an untagged type, and there
4760       --  are no constraints involved (could be more general???)
4761
4762       elsif Etype (Ityp) = Otyp
4763         and then not Is_Tagged_Type (Ityp)
4764         and then not Has_Discriminants (Ityp)
4765         and then No (First_Rep_Item (Base_Type (Ityp)))
4766       then
4767          return True;
4768
4769       --  If the size of output type is known at compile time, there is
4770       --  never a problem.  Note that unconstrained records are considered
4771       --  to be of known size, but we can't consider them that way here,
4772       --  because we are talking about the actual size of the object.
4773
4774       --  We also make sure that in addition to the size being known, we do
4775       --  not have a case which might generate an embarrassingly large temp
4776       --  in stack checking mode.
4777
4778       elsif Size_Known_At_Compile_Time (Otyp)
4779         and then
4780           (not Stack_Checking_Enabled
4781              or else not May_Generate_Large_Temp (Otyp))
4782         and then not (Is_Record_Type (Otyp) and then not Is_Constrained (Otyp))
4783       then
4784          return True;
4785
4786       --  If either type is tagged, then we know the alignment is OK so
4787       --  Gigi will be able to use pointer punning.
4788
4789       elsif Is_Tagged_Type (Otyp) or else Is_Tagged_Type (Ityp) then
4790          return True;
4791
4792       --  If either type is a limited record type, we cannot do a copy, so
4793       --  say safe since there's nothing else we can do.
4794
4795       elsif Is_Limited_Record (Otyp) or else Is_Limited_Record (Ityp) then
4796          return True;
4797
4798       --  Conversions to and from packed array types are always ignored and
4799       --  hence are safe.
4800
4801       elsif Is_Packed_Array_Type (Otyp)
4802         or else Is_Packed_Array_Type (Ityp)
4803       then
4804          return True;
4805       end if;
4806
4807       --  The only other cases known to be safe is if the input type's
4808       --  alignment is known to be at least the maximum alignment for the
4809       --  target or if both alignments are known and the output type's
4810       --  alignment is no stricter than the input's.  We can use the alignment
4811       --  of the component type of an array if a type is an unpacked
4812       --  array type.
4813
4814       if Present (Alignment_Clause (Otyp)) then
4815          Oalign := Expr_Value (Expression (Alignment_Clause (Otyp)));
4816
4817       elsif Is_Array_Type (Otyp)
4818         and then Present (Alignment_Clause (Component_Type (Otyp)))
4819       then
4820          Oalign := Expr_Value (Expression (Alignment_Clause
4821                                            (Component_Type (Otyp))));
4822       end if;
4823
4824       if Present (Alignment_Clause (Ityp)) then
4825          Ialign := Expr_Value (Expression (Alignment_Clause (Ityp)));
4826
4827       elsif Is_Array_Type (Ityp)
4828         and then Present (Alignment_Clause (Component_Type (Ityp)))
4829       then
4830          Ialign := Expr_Value (Expression (Alignment_Clause
4831                                            (Component_Type (Ityp))));
4832       end if;
4833
4834       if Ialign /= No_Uint and then Ialign > Maximum_Alignment then
4835          return True;
4836
4837       elsif Ialign /= No_Uint and then Oalign /= No_Uint
4838         and then Ialign <= Oalign
4839       then
4840          return True;
4841
4842       --   Otherwise, Gigi cannot handle this and we must make a temporary
4843
4844       else
4845          return False;
4846       end if;
4847    end Safe_Unchecked_Type_Conversion;
4848
4849    ---------------------------------
4850    -- Set_Current_Value_Condition --
4851    ---------------------------------
4852
4853    --  Note: the implementation of this procedure is very closely tied to the
4854    --  implementation of Get_Current_Value_Condition. Here we set required
4855    --  Current_Value fields, and in Get_Current_Value_Condition, we interpret
4856    --  them, so they must have a consistent view.
4857
4858    procedure Set_Current_Value_Condition (Cnode : Node_Id) is
4859
4860       procedure Set_Entity_Current_Value (N : Node_Id);
4861       --  If N is an entity reference, where the entity is of an appropriate
4862       --  kind, then set the current value of this entity to Cnode, unless
4863       --  there is already a definite value set there.
4864
4865       procedure Set_Expression_Current_Value (N : Node_Id);
4866       --  If N is of an appropriate form, sets an appropriate entry in current
4867       --  value fields of relevant entities. Multiple entities can be affected
4868       --  in the case of an AND or AND THEN.
4869
4870       ------------------------------
4871       -- Set_Entity_Current_Value --
4872       ------------------------------
4873
4874       procedure Set_Entity_Current_Value (N : Node_Id) is
4875       begin
4876          if Is_Entity_Name (N) then
4877             declare
4878                Ent : constant Entity_Id := Entity (N);
4879
4880             begin
4881                --  Don't capture if not safe to do so
4882
4883                if not Safe_To_Capture_Value (N, Ent, Cond => True) then
4884                   return;
4885                end if;
4886
4887                --  Here we have a case where the Current_Value field may
4888                --  need to be set. We set it if it is not already set to a
4889                --  compile time expression value.
4890
4891                --  Note that this represents a decision that one condition
4892                --  blots out another previous one. That's certainly right
4893                --  if they occur at the same level. If the second one is
4894                --  nested, then the decision is neither right nor wrong (it
4895                --  would be equally OK to leave the outer one in place, or
4896                --  take the new inner one. Really we should record both, but
4897                --  our data structures are not that elaborate.
4898
4899                if Nkind (Current_Value (Ent)) not in N_Subexpr then
4900                   Set_Current_Value (Ent, Cnode);
4901                end if;
4902             end;
4903          end if;
4904       end Set_Entity_Current_Value;
4905
4906       ----------------------------------
4907       -- Set_Expression_Current_Value --
4908       ----------------------------------
4909
4910       procedure Set_Expression_Current_Value (N : Node_Id) is
4911          Cond : Node_Id;
4912
4913       begin
4914          Cond := N;
4915
4916          --  Loop to deal with (ignore for now) any NOT operators present. The
4917          --  presence of NOT operators will be handled properly when we call
4918          --  Get_Current_Value_Condition.
4919
4920          while Nkind (Cond) = N_Op_Not loop
4921             Cond := Right_Opnd (Cond);
4922          end loop;
4923
4924          --  For an AND or AND THEN, recursively process operands
4925
4926          if Nkind (Cond) = N_Op_And or else Nkind (Cond) = N_And_Then then
4927             Set_Expression_Current_Value (Left_Opnd (Cond));
4928             Set_Expression_Current_Value (Right_Opnd (Cond));
4929             return;
4930          end if;
4931
4932          --  Check possible relational operator
4933
4934          if Nkind (Cond) in N_Op_Compare then
4935             if Compile_Time_Known_Value (Right_Opnd (Cond)) then
4936                Set_Entity_Current_Value (Left_Opnd (Cond));
4937             elsif Compile_Time_Known_Value (Left_Opnd (Cond)) then
4938                Set_Entity_Current_Value (Right_Opnd (Cond));
4939             end if;
4940
4941             --  Check possible boolean variable reference
4942
4943          else
4944             Set_Entity_Current_Value (Cond);
4945          end if;
4946       end Set_Expression_Current_Value;
4947
4948    --  Start of processing for Set_Current_Value_Condition
4949
4950    begin
4951       Set_Expression_Current_Value (Condition (Cnode));
4952    end Set_Current_Value_Condition;
4953
4954    --------------------------
4955    -- Set_Elaboration_Flag --
4956    --------------------------
4957
4958    procedure Set_Elaboration_Flag (N : Node_Id; Spec_Id : Entity_Id) is
4959       Loc : constant Source_Ptr := Sloc (N);
4960       Ent : constant Entity_Id  := Elaboration_Entity (Spec_Id);
4961       Asn : Node_Id;
4962
4963    begin
4964       if Present (Ent) then
4965
4966          --  Nothing to do if at the compilation unit level, because in this
4967          --  case the flag is set by the binder generated elaboration routine.
4968
4969          if Nkind (Parent (N)) = N_Compilation_Unit then
4970             null;
4971
4972          --  Here we do need to generate an assignment statement
4973
4974          else
4975             Check_Restriction (No_Elaboration_Code, N);
4976             Asn :=
4977               Make_Assignment_Statement (Loc,
4978                 Name       => New_Occurrence_Of (Ent, Loc),
4979                 Expression => New_Occurrence_Of (Standard_True, Loc));
4980
4981             if Nkind (Parent (N)) = N_Subunit then
4982                Insert_After (Corresponding_Stub (Parent (N)), Asn);
4983             else
4984                Insert_After (N, Asn);
4985             end if;
4986
4987             Analyze (Asn);
4988
4989             --  Kill current value indication. This is necessary because
4990             --  the tests of this flag are inserted out of sequence and must
4991             --  not pick up bogus indications of the wrong constant value.
4992
4993             Set_Current_Value (Ent, Empty);
4994          end if;
4995       end if;
4996    end Set_Elaboration_Flag;
4997
4998    ----------------------------
4999    -- Set_Renamed_Subprogram --
5000    ----------------------------
5001
5002    procedure Set_Renamed_Subprogram (N : Node_Id; E : Entity_Id) is
5003    begin
5004       --  If input node is an identifier, we can just reset it
5005
5006       if Nkind (N) = N_Identifier then
5007          Set_Chars  (N, Chars (E));
5008          Set_Entity (N, E);
5009
5010          --  Otherwise we have to do a rewrite, preserving Comes_From_Source
5011
5012       else
5013          declare
5014             CS : constant Boolean := Comes_From_Source (N);
5015          begin
5016             Rewrite (N, Make_Identifier (Sloc (N), Chars => Chars (E)));
5017             Set_Entity (N, E);
5018             Set_Comes_From_Source (N, CS);
5019             Set_Analyzed (N, True);
5020          end;
5021       end if;
5022    end Set_Renamed_Subprogram;
5023
5024    --------------------------
5025    -- Target_Has_Fixed_Ops --
5026    --------------------------
5027
5028    Integer_Sized_Small : Ureal;
5029    --  Set to 2.0 ** -(Integer'Size - 1) the first time that this
5030    --  function is called (we don't want to compute it more than once!)
5031
5032    Long_Integer_Sized_Small : Ureal;
5033    --  Set to 2.0 ** -(Long_Integer'Size - 1) the first time that this
5034    --  functoin is called (we don't want to compute it more than once)
5035
5036    First_Time_For_THFO : Boolean := True;
5037    --  Set to False after first call (if Fractional_Fixed_Ops_On_Target)
5038
5039    function Target_Has_Fixed_Ops
5040      (Left_Typ   : Entity_Id;
5041       Right_Typ  : Entity_Id;
5042       Result_Typ : Entity_Id) return Boolean
5043    is
5044       function Is_Fractional_Type (Typ : Entity_Id) return Boolean;
5045       --  Return True if the given type is a fixed-point type with a small
5046       --  value equal to 2 ** (-(T'Object_Size - 1)) and whose values have
5047       --  an absolute value less than 1.0. This is currently limited
5048       --  to fixed-point types that map to Integer or Long_Integer.
5049
5050       ------------------------
5051       -- Is_Fractional_Type --
5052       ------------------------
5053
5054       function Is_Fractional_Type (Typ : Entity_Id) return Boolean is
5055       begin
5056          if Esize (Typ) = Standard_Integer_Size then
5057             return Small_Value (Typ) = Integer_Sized_Small;
5058
5059          elsif Esize (Typ) = Standard_Long_Integer_Size then
5060             return Small_Value (Typ) = Long_Integer_Sized_Small;
5061
5062          else
5063             return False;
5064          end if;
5065       end Is_Fractional_Type;
5066
5067    --  Start of processing for Target_Has_Fixed_Ops
5068
5069    begin
5070       --  Return False if Fractional_Fixed_Ops_On_Target is false
5071
5072       if not Fractional_Fixed_Ops_On_Target then
5073          return False;
5074       end if;
5075
5076       --  Here the target has Fractional_Fixed_Ops, if first time, compute
5077       --  standard constants used by Is_Fractional_Type.
5078
5079       if First_Time_For_THFO then
5080          First_Time_For_THFO := False;
5081
5082          Integer_Sized_Small :=
5083            UR_From_Components
5084              (Num   => Uint_1,
5085               Den   => UI_From_Int (Standard_Integer_Size - 1),
5086               Rbase => 2);
5087
5088          Long_Integer_Sized_Small :=
5089            UR_From_Components
5090              (Num   => Uint_1,
5091               Den   => UI_From_Int (Standard_Long_Integer_Size - 1),
5092               Rbase => 2);
5093       end if;
5094
5095       --  Return True if target supports fixed-by-fixed multiply/divide
5096       --  for fractional fixed-point types (see Is_Fractional_Type) and
5097       --  the operand and result types are equivalent fractional types.
5098
5099       return Is_Fractional_Type (Base_Type (Left_Typ))
5100         and then Is_Fractional_Type (Base_Type (Right_Typ))
5101         and then Is_Fractional_Type (Base_Type (Result_Typ))
5102         and then Esize (Left_Typ) = Esize (Right_Typ)
5103         and then Esize (Left_Typ) = Esize (Result_Typ);
5104    end Target_Has_Fixed_Ops;
5105
5106    ------------------------------------------
5107    -- Type_May_Have_Bit_Aligned_Components --
5108    ------------------------------------------
5109
5110    function Type_May_Have_Bit_Aligned_Components
5111      (Typ : Entity_Id) return Boolean
5112    is
5113    begin
5114       --  Array type, check component type
5115
5116       if Is_Array_Type (Typ) then
5117          return
5118            Type_May_Have_Bit_Aligned_Components (Component_Type (Typ));
5119
5120       --  Record type, check components
5121
5122       elsif Is_Record_Type (Typ) then
5123          declare
5124             E : Entity_Id;
5125
5126          begin
5127             E := First_Entity (Typ);
5128             while Present (E) loop
5129                if Ekind (E) = E_Component
5130                  or else Ekind (E) = E_Discriminant
5131                then
5132                   if Component_May_Be_Bit_Aligned (E)
5133                     or else
5134                       Type_May_Have_Bit_Aligned_Components (Etype (E))
5135                   then
5136                      return True;
5137                   end if;
5138                end if;
5139
5140                Next_Entity (E);
5141             end loop;
5142
5143             return False;
5144          end;
5145
5146       --  Type other than array or record is always OK
5147
5148       else
5149          return False;
5150       end if;
5151    end Type_May_Have_Bit_Aligned_Components;
5152
5153    ----------------------------
5154    -- Wrap_Cleanup_Procedure --
5155    ----------------------------
5156
5157    procedure Wrap_Cleanup_Procedure (N : Node_Id) is
5158       Loc   : constant Source_Ptr := Sloc (N);
5159       Stseq : constant Node_Id    := Handled_Statement_Sequence (N);
5160       Stmts : constant List_Id    := Statements (Stseq);
5161
5162    begin
5163       if Abort_Allowed then
5164          Prepend_To (Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer));
5165          Append_To  (Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer));
5166       end if;
5167    end Wrap_Cleanup_Procedure;
5168
5169 end Exp_Util;