OSDN Git Service

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