OSDN Git Service

2010-10-22 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch7.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 7                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, 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 --  This package contains virtually all expansion mechanisms related to
27 --    - controlled types
28 --    - transient scopes
29
30 with Atree;    use Atree;
31 with Debug;    use Debug;
32 with Einfo;    use Einfo;
33 with Errout;   use Errout;
34 with Exp_Ch9;  use Exp_Ch9;
35 with Exp_Ch11; use Exp_Ch11;
36 with Exp_Dbug; use Exp_Dbug;
37 with Exp_Dist; use Exp_Dist;
38 with Exp_Disp; use Exp_Disp;
39 with Exp_Tss;  use Exp_Tss;
40 with Exp_Util; use Exp_Util;
41 with Freeze;   use Freeze;
42 with Lib;      use Lib;
43 with Nlists;   use Nlists;
44 with Nmake;    use Nmake;
45 with Opt;      use Opt;
46 with Output;   use Output;
47 with Restrict; use Restrict;
48 with Rident;   use Rident;
49 with Rtsfind;  use Rtsfind;
50 with Sinfo;    use Sinfo;
51 with Sem;      use Sem;
52 with Sem_Aux;  use Sem_Aux;
53 with Sem_Ch3;  use Sem_Ch3;
54 with Sem_Ch7;  use Sem_Ch7;
55 with Sem_Ch8;  use Sem_Ch8;
56 with Sem_Res;  use Sem_Res;
57 with Sem_Type; use Sem_Type;
58 with Sem_Util; use Sem_Util;
59 with Snames;   use Snames;
60 with Stand;    use Stand;
61 with Targparm; use Targparm;
62 with Tbuild;   use Tbuild;
63 with Uintp;    use Uintp;
64
65 package body Exp_Ch7 is
66
67    --------------------------------
68    -- Transient Scope Management --
69    --------------------------------
70
71    --  A transient scope is created when temporary objects are created by the
72    --  compiler. These temporary objects are allocated on the secondary stack
73    --  and the transient scope is responsible for finalizing the object when
74    --  appropriate and reclaiming the memory at the right time. The temporary
75    --  objects are generally the objects allocated to store the result of a
76    --  function returning an unconstrained or a tagged value. Expressions
77    --  needing to be wrapped in a transient scope (functions calls returning
78    --  unconstrained or tagged values) may appear in 3 different contexts which
79    --  lead to 3 different kinds of transient scope expansion:
80
81    --   1. In a simple statement (procedure call, assignment, ...). In
82    --      this case the instruction is wrapped into a transient block.
83    --      (See Wrap_Transient_Statement for details)
84
85    --   2. In an expression of a control structure (test in a IF statement,
86    --      expression in a CASE statement, ...).
87    --      (See Wrap_Transient_Expression for details)
88
89    --   3. In a expression of an object_declaration. No wrapping is possible
90    --      here, so the finalization actions, if any, are done right after the
91    --      declaration and the secondary stack deallocation is done in the
92    --      proper enclosing scope (see Wrap_Transient_Declaration for details)
93
94    --  Note about functions returning tagged types: it has been decided to
95    --  always allocate their result in the secondary stack, even though is not
96    --  absolutely mandatory when the tagged type is constrained because the
97    --  caller knows the size of the returned object and thus could allocate the
98    --  result in the primary stack. An exception to this is when the function
99    --  builds its result in place, as is done for functions with inherently
100    --  limited result types for Ada 2005. In that case, certain callers may
101    --  pass the address of a constrained object as the target object for the
102    --  function result.
103
104    --  By allocating tagged results in the secondary stack a number of
105    --  implementation difficulties are avoided:
106
107    --    - If it is a dispatching function call, the computation of the size of
108    --      the result is possible but complex from the outside.
109
110    --    - If the returned type is controlled, the assignment of the returned
111    --      value to the anonymous object involves an Adjust, and we have no
112    --      easy way to access the anonymous object created by the back end.
113
114    --    - If the returned type is class-wide, this is an unconstrained type
115    --      anyway.
116
117    --  Furthermore, the small loss in efficiency which is the result of this
118    --  decision is not such a big deal because functions returning tagged types
119    --  are not as common in practice compared to functions returning access to
120    --  a tagged type.
121
122    --------------------------------------------------
123    -- Transient Blocks and Finalization Management --
124    --------------------------------------------------
125
126    function Find_Node_To_Be_Wrapped (N : Node_Id) return Node_Id;
127    --  N is a node which may generate a transient scope. Loop over the parent
128    --  pointers of N until it find the appropriate node to wrap. If it returns
129    --  Empty, it means that no transient scope is needed in this context.
130
131    function Make_Clean
132      (N                          : Node_Id;
133       Clean                      : Entity_Id;
134       Mark                       : Entity_Id;
135       Flist                      : Entity_Id;
136       Is_Task                    : Boolean;
137       Is_Master                  : Boolean;
138       Is_Protected_Subprogram    : Boolean;
139       Is_Task_Allocation_Block   : Boolean;
140       Is_Asynchronous_Call_Block : Boolean;
141       Chained_Cleanup_Action     : Node_Id) return Node_Id;
142    --  Expand the clean-up procedure for a controlled and/or transient block,
143    --  and/or task master or task body, or a block used to  implement task
144    --  allocation or asynchronous entry calls, or a procedure used to implement
145    --  protected procedures. Clean is the entity for such a procedure. Mark
146    --  is the entity for the secondary stack mark, if empty only controlled
147    --  block clean-up will be performed. Flist is the entity for the local
148    --  final list, if empty only transient scope clean-up will be performed.
149    --  The flags Is_Task and Is_Master control the calls to the corresponding
150    --  finalization actions for a task body or for an entity that is a task
151    --  master. Finally if Chained_Cleanup_Action is present, it is a reference
152    --  to a previous cleanup procedure, a call to which is appended at the
153    --  end of the generated one.
154
155    procedure Set_Node_To_Be_Wrapped (N : Node_Id);
156    --  Set the field Node_To_Be_Wrapped of the current scope
157
158    procedure Insert_Actions_In_Scope_Around (N : Node_Id);
159    --  Insert the before-actions kept in the scope stack before N, and the
160    --  after-actions after N, which must be a member of a list.
161
162    function Make_Transient_Block
163      (Loc    : Source_Ptr;
164       Action : Node_Id) return Node_Id;
165    --  Create a transient block whose name is Scope, which is also a controlled
166    --  block if Flist is not empty and whose only code is Action (either a
167    --  single statement or single declaration).
168
169    type Final_Primitives is (Initialize_Case, Adjust_Case, Finalize_Case);
170    --  This enumeration type is defined in order to ease sharing code for
171    --  building finalization procedures for composite types.
172
173    Name_Of      : constant array (Final_Primitives) of Name_Id :=
174                     (Initialize_Case => Name_Initialize,
175                      Adjust_Case     => Name_Adjust,
176                      Finalize_Case   => Name_Finalize);
177
178    Deep_Name_Of : constant array (Final_Primitives) of TSS_Name_Type :=
179                     (Initialize_Case => TSS_Deep_Initialize,
180                      Adjust_Case     => TSS_Deep_Adjust,
181                      Finalize_Case   => TSS_Deep_Finalize);
182
183    procedure Build_Record_Deep_Procs (Typ : Entity_Id);
184    --  Build the deep Initialize/Adjust/Finalize for a record Typ with
185    --  Has_Component_Component set and store them using the TSS mechanism.
186
187    procedure Build_Array_Deep_Procs (Typ : Entity_Id);
188    --  Build the deep Initialize/Adjust/Finalize for a record Typ with
189    --  Has_Controlled_Component set and store them using the TSS mechanism.
190
191    function Make_Deep_Proc
192      (Prim  : Final_Primitives;
193       Typ   : Entity_Id;
194       Stmts : List_Id) return Node_Id;
195    --  This function generates the tree for Deep_Initialize, Deep_Adjust or
196    --  Deep_Finalize procedures according to the first parameter, these
197    --  procedures operate on the type Typ. The Stmts parameter gives the body
198    --  of the procedure.
199
200    function Make_Deep_Array_Body
201      (Prim : Final_Primitives;
202       Typ  : Entity_Id) return List_Id;
203    --  This function generates the list of statements for implementing
204    --  Deep_Initialize, Deep_Adjust or Deep_Finalize procedures according to
205    --  the first parameter, these procedures operate on the array type Typ.
206
207    function Make_Deep_Record_Body
208      (Prim : Final_Primitives;
209       Typ  : Entity_Id) return List_Id;
210    --  This function generates the list of statements for implementing
211    --  Deep_Initialize, Deep_Adjust or Deep_Finalize procedures according to
212    --  the first parameter, these procedures operate on the record type Typ.
213
214    procedure Check_Visibly_Controlled
215      (Prim : Final_Primitives;
216       Typ  : Entity_Id;
217       E    : in out Entity_Id;
218       Cref : in out Node_Id);
219    --  The controlled operation declared for a derived type may not be
220    --  overriding, if the controlled operations of the parent type are
221    --  hidden, for example when the parent is a private type whose full
222    --  view is controlled. For other primitive operations we modify the
223    --  name of the operation to indicate that it is not overriding, but
224    --  this is not possible for Initialize, etc. because they have to be
225    --  retrievable by name. Before generating the proper call to one of
226    --  these operations we check whether Typ is known to be controlled at
227    --  the point of definition. If it is not then we must retrieve the
228    --  hidden operation of the parent and use it instead.  This is one
229    --  case that might be solved more cleanly once Overriding pragmas or
230    --  declarations are in place.
231
232    function Convert_View
233      (Proc : Entity_Id;
234       Arg  : Node_Id;
235       Ind  : Pos := 1) return Node_Id;
236    --  Proc is one of the Initialize/Adjust/Finalize operations, and
237    --  Arg is the argument being passed to it. Ind indicates which
238    --  formal of procedure Proc we are trying to match. This function
239    --  will, if necessary, generate an conversion between the partial
240    --  and full view of Arg to match the type of the formal of Proc,
241    --  or force a conversion to the class-wide type in the case where
242    --  the operation is abstract.
243
244    -----------------------------
245    -- Finalization Management --
246    -----------------------------
247
248    --  This part describe how Initialization/Adjustment/Finalization procedures
249    --  are generated and called. Two cases must be considered, types that are
250    --  Controlled (Is_Controlled flag set) and composite types that contain
251    --  controlled components (Has_Controlled_Component flag set). In the first
252    --  case the procedures to call are the user-defined primitive operations
253    --  Initialize/Adjust/Finalize. In the second case, GNAT generates
254    --  Deep_Initialize, Deep_Adjust and Deep_Finalize that are in charge
255    --  of calling the former procedures on the controlled components.
256
257    --  For records with Has_Controlled_Component set, a hidden "controller"
258    --  component is inserted. This controller component contains its own
259    --  finalization list on which all controlled components are attached
260    --  creating an indirection on the upper-level Finalization list. This
261    --  technique facilitates the management of objects whose number of
262    --  controlled components changes during execution. This controller
263    --  component is itself controlled and is attached to the upper-level
264    --  finalization chain. Its adjust primitive is in charge of calling adjust
265    --  on the components and adjusting the finalization pointer to match their
266    --  new location (see a-finali.adb).
267
268    --  It is not possible to use a similar technique for arrays that have
269    --  Has_Controlled_Component set. In this case, deep procedures are
270    --  generated that call initialize/adjust/finalize + attachment or
271    --  detachment on the finalization list for all component.
272
273    --  Initialize calls: they are generated for declarations or dynamic
274    --  allocations of Controlled objects with no initial value. They are always
275    --  followed by an attachment to the current Finalization Chain. For the
276    --  dynamic allocation case this the chain attached to the scope of the
277    --  access type definition otherwise, this is the chain of the current
278    --  scope.
279
280    --  Adjust Calls: They are generated on 2 occasions: (1) for
281    --  declarations or dynamic allocations of Controlled objects with an
282    --  initial value. (2) after an assignment. In the first case they are
283    --  followed by an attachment to the final chain, in the second case
284    --  they are not.
285
286    --  Finalization Calls: They are generated on (1) scope exit, (2)
287    --  assignments, (3) unchecked deallocations. In case (3) they have to
288    --  be detached from the final chain, in case (2) they must not and in
289    --  case (1) this is not important since we are exiting the scope anyway.
290
291    --  Other details:
292
293    --    Type extensions will have a new record controller at each derivation
294    --    level containing controlled components. The record controller for
295    --    the parent/ancestor is attached to the finalization list of the
296    --    extension's record controller (i.e. the parent is like a component
297    --    of the extension).
298
299    --    For types that are both Is_Controlled and Has_Controlled_Components,
300    --    the record controller and the object itself are handled separately.
301    --    It could seem simpler to attach the object at the end of its record
302    --    controller but this would not tackle view conversions properly.
303
304    --    A classwide type can always potentially have controlled components
305    --    but the record controller of the corresponding actual type may not
306    --    be known at compile time so the dispatch table contains a special
307    --    field that allows to compute the offset of the record controller
308    --    dynamically. See s-finimp.Deep_Tag_Attach and a-tags.RC_Offset.
309
310    --  Here is a simple example of the expansion of a controlled block :
311
312    --    declare
313    --       X : Controlled;
314    --       Y : Controlled := Init;
315    --
316    --       type R is record
317    --          C : Controlled;
318    --       end record;
319    --       W : R;
320    --       Z : R := (C => X);
321    --    begin
322    --       X := Y;
323    --       W := Z;
324    --    end;
325    --
326    --  is expanded into
327    --
328    --    declare
329    --       _L : System.FI.Finalizable_Ptr;
330
331    --       procedure _Clean is
332    --       begin
333    --          Abort_Defer;
334    --          System.FI.Finalize_List (_L);
335    --          Abort_Undefer;
336    --       end _Clean;
337
338    --       X : Controlled;
339    --       begin
340    --          Abort_Defer;
341    --          Initialize (X);
342    --          Attach_To_Final_List (_L, Finalizable (X), 1);
343    --       at end: Abort_Undefer;
344    --       Y : Controlled := Init;
345    --       Adjust (Y);
346    --       Attach_To_Final_List (_L, Finalizable (Y), 1);
347    --
348    --       type R is record
349    --         _C : Record_Controller;
350    --          C : Controlled;
351    --       end record;
352    --       W : R;
353    --       begin
354    --          Abort_Defer;
355    --          Deep_Initialize (W, _L, 1);
356    --       at end: Abort_Under;
357    --       Z : R := (C => X);
358    --       Deep_Adjust (Z, _L, 1);
359
360    --    begin
361    --       _Assign (X, Y);
362    --       Deep_Finalize (W, False);
363    --       <save W's final pointers>
364    --       W := Z;
365    --       <restore W's final pointers>
366    --       Deep_Adjust (W, _L, 0);
367    --    at end
368    --       _Clean;
369    --    end;
370
371    function Global_Flist_Ref (Flist_Ref : Node_Id) return Boolean;
372    --  Return True if Flist_Ref refers to a global final list, either the
373    --  object Global_Final_List which is used to attach standalone objects,
374    --  or any of the list controllers associated with library-level access
375    --  to controlled objects.
376
377    procedure Clean_Simple_Protected_Objects (N : Node_Id);
378    --  Protected objects without entries are not controlled types, and the
379    --  locks have to be released explicitly when such an object goes out
380    --  of scope. Traverse declarations in scope to determine whether such
381    --  objects are present.
382
383    ----------------------------
384    -- Build_Array_Deep_Procs --
385    ----------------------------
386
387    procedure Build_Array_Deep_Procs (Typ : Entity_Id) is
388    begin
389       Set_TSS (Typ,
390         Make_Deep_Proc (
391           Prim  => Initialize_Case,
392           Typ   => Typ,
393           Stmts => Make_Deep_Array_Body (Initialize_Case, Typ)));
394
395       if not Is_Immutably_Limited_Type (Typ) then
396          Set_TSS (Typ,
397            Make_Deep_Proc (
398              Prim  => Adjust_Case,
399              Typ   => Typ,
400              Stmts => Make_Deep_Array_Body (Adjust_Case, Typ)));
401       end if;
402
403       Set_TSS (Typ,
404         Make_Deep_Proc (
405           Prim  => Finalize_Case,
406           Typ   => Typ,
407           Stmts => Make_Deep_Array_Body (Finalize_Case, Typ)));
408    end Build_Array_Deep_Procs;
409
410    -----------------------------
411    -- Build_Controlling_Procs --
412    -----------------------------
413
414    procedure Build_Controlling_Procs (Typ : Entity_Id) is
415    begin
416       if Is_Array_Type (Typ) then
417          Build_Array_Deep_Procs (Typ);
418
419       else pragma Assert (Is_Record_Type (Typ));
420          Build_Record_Deep_Procs (Typ);
421       end if;
422    end Build_Controlling_Procs;
423
424    ----------------------
425    -- Build_Final_List --
426    ----------------------
427
428    procedure Build_Final_List (N : Node_Id; Typ : Entity_Id) is
429       Loc  : constant Source_Ptr := Sloc (N);
430       Decl : Node_Id;
431
432    begin
433       Set_Associated_Final_Chain (Typ,
434         Make_Defining_Identifier (Loc,
435           New_External_Name (Chars (Typ), 'L')));
436
437       Decl :=
438         Make_Object_Declaration (Loc,
439           Defining_Identifier =>
440              Associated_Final_Chain (Typ),
441           Object_Definition   =>
442             New_Reference_To
443               (RTE (RE_List_Controller), Loc));
444
445       --  If the type is declared in a package declaration and designates a
446       --  Taft amendment type that requires finalization, place declaration
447       --  of finalization list in the body, because no client of the package
448       --  can create objects of the type and thus make use of this list. This
449       --  ensures the tree for the spec is identical whenever it is compiled.
450
451       if Has_Completion_In_Body (Directly_Designated_Type (Typ))
452         and then In_Package_Body (Current_Scope)
453         and then Nkind (Unit (Cunit (Current_Sem_Unit))) = N_Package_Body
454         and then
455           Nkind (Parent (Declaration_Node (Typ))) = N_Package_Specification
456       then
457          Insert_Action (Parent (Designated_Type (Typ)), Decl);
458
459       --  The type may have been frozen already, and this is a late freezing
460       --  action, in which case the declaration must be elaborated at once.
461       --  If the call is for an allocator, the chain must also be created now,
462       --  because the freezing of the type does not build one. Otherwise, the
463       --  declaration is one of the freezing actions for a user-defined type.
464
465       elsif Is_Frozen (Typ)
466         or else (Nkind (N) = N_Allocator
467                   and then Ekind (Etype (N)) = E_Anonymous_Access_Type)
468       then
469          Insert_Action (N, Decl);
470
471       else
472          Append_Freeze_Action (Typ, Decl);
473       end if;
474    end Build_Final_List;
475
476    ---------------------
477    -- Build_Late_Proc --
478    ---------------------
479
480    procedure Build_Late_Proc (Typ : Entity_Id; Nam : Name_Id) is
481    begin
482       for Final_Prim in Name_Of'Range loop
483          if Name_Of (Final_Prim) = Nam then
484             Set_TSS (Typ,
485               Make_Deep_Proc (
486                 Prim  => Final_Prim,
487                 Typ   => Typ,
488                 Stmts => Make_Deep_Record_Body (Final_Prim, Typ)));
489          end if;
490       end loop;
491    end Build_Late_Proc;
492
493    -----------------------------
494    -- Build_Record_Deep_Procs --
495    -----------------------------
496
497    procedure Build_Record_Deep_Procs (Typ : Entity_Id) is
498    begin
499       Set_TSS (Typ,
500         Make_Deep_Proc (
501           Prim  => Initialize_Case,
502           Typ   => Typ,
503           Stmts => Make_Deep_Record_Body (Initialize_Case, Typ)));
504
505       if not Is_Immutably_Limited_Type (Typ) then
506          Set_TSS (Typ,
507            Make_Deep_Proc (
508              Prim  => Adjust_Case,
509              Typ   => Typ,
510              Stmts => Make_Deep_Record_Body (Adjust_Case, Typ)));
511       end if;
512
513       Set_TSS (Typ,
514         Make_Deep_Proc (
515           Prim  => Finalize_Case,
516           Typ   => Typ,
517           Stmts => Make_Deep_Record_Body (Finalize_Case, Typ)));
518    end Build_Record_Deep_Procs;
519
520    -------------------
521    -- Cleanup_Array --
522    -------------------
523
524    function Cleanup_Array
525      (N    : Node_Id;
526       Obj  : Node_Id;
527       Typ  : Entity_Id) return List_Id
528    is
529       Loc        : constant Source_Ptr := Sloc (N);
530       Index_List : constant List_Id := New_List;
531
532       function Free_Component return List_Id;
533       --  Generate the code to finalize the task or protected  subcomponents
534       --  of a single component of the array.
535
536       function Free_One_Dimension (Dim : Int) return List_Id;
537       --  Generate a loop over one dimension of the array
538
539       --------------------
540       -- Free_Component --
541       --------------------
542
543       function Free_Component return List_Id is
544          Stmts : List_Id := New_List;
545          Tsk   : Node_Id;
546          C_Typ : constant Entity_Id := Component_Type (Typ);
547
548       begin
549          --  Component type is known to contain tasks or protected objects
550
551          Tsk :=
552            Make_Indexed_Component (Loc,
553              Prefix        => Duplicate_Subexpr_No_Checks (Obj),
554              Expressions   => Index_List);
555
556          Set_Etype (Tsk, C_Typ);
557
558          if Is_Task_Type (C_Typ) then
559             Append_To (Stmts, Cleanup_Task (N, Tsk));
560
561          elsif Is_Simple_Protected_Type (C_Typ) then
562             Append_To (Stmts, Cleanup_Protected_Object (N, Tsk));
563
564          elsif Is_Record_Type (C_Typ) then
565             Stmts := Cleanup_Record (N, Tsk, C_Typ);
566
567          elsif Is_Array_Type (C_Typ) then
568             Stmts := Cleanup_Array (N, Tsk, C_Typ);
569          end if;
570
571          return Stmts;
572       end Free_Component;
573
574       ------------------------
575       -- Free_One_Dimension --
576       ------------------------
577
578       function Free_One_Dimension (Dim : Int) return List_Id is
579          Index      : Entity_Id;
580
581       begin
582          if Dim > Number_Dimensions (Typ) then
583             return Free_Component;
584
585          --  Here we generate the required loop
586
587          else
588             Index := Make_Temporary (Loc, 'J');
589             Append (New_Reference_To (Index, Loc), Index_List);
590
591             return New_List (
592               Make_Implicit_Loop_Statement (N,
593                 Identifier => Empty,
594                 Iteration_Scheme =>
595                   Make_Iteration_Scheme (Loc,
596                     Loop_Parameter_Specification =>
597                       Make_Loop_Parameter_Specification (Loc,
598                         Defining_Identifier => Index,
599                         Discrete_Subtype_Definition =>
600                           Make_Attribute_Reference (Loc,
601                             Prefix => Duplicate_Subexpr (Obj),
602                             Attribute_Name  => Name_Range,
603                             Expressions => New_List (
604                               Make_Integer_Literal (Loc, Dim))))),
605                 Statements =>  Free_One_Dimension (Dim + 1)));
606          end if;
607       end Free_One_Dimension;
608
609    --  Start of processing for Cleanup_Array
610
611    begin
612       return Free_One_Dimension (1);
613    end Cleanup_Array;
614
615    --------------------
616    -- Cleanup_Record --
617    --------------------
618
619    function Cleanup_Record
620      (N    : Node_Id;
621       Obj  : Node_Id;
622       Typ  : Entity_Id) return List_Id
623    is
624       Loc   : constant Source_Ptr := Sloc (N);
625       Tsk   : Node_Id;
626       Comp  : Entity_Id;
627       Stmts : constant List_Id    := New_List;
628       U_Typ : constant Entity_Id  := Underlying_Type (Typ);
629
630    begin
631       if Has_Discriminants (U_Typ)
632         and then Nkind (Parent (U_Typ)) = N_Full_Type_Declaration
633         and then
634           Nkind (Type_Definition (Parent (U_Typ))) = N_Record_Definition
635         and then
636           Present
637             (Variant_Part
638               (Component_List (Type_Definition (Parent (U_Typ)))))
639       then
640          --  For now, do not attempt to free a component that may appear in
641          --  a variant, and instead issue a warning. Doing this "properly"
642          --  would require building a case statement and would be quite a
643          --  mess. Note that the RM only requires that free "work" for the
644          --  case of a task access value, so already we go way beyond this
645          --  in that we deal with the array case and non-discriminated
646          --  record cases.
647
648          Error_Msg_N
649            ("task/protected object in variant record will not be freed?", N);
650          return New_List (Make_Null_Statement (Loc));
651       end if;
652
653       Comp := First_Component (Typ);
654
655       while Present (Comp) loop
656          if Has_Task (Etype (Comp))
657            or else Has_Simple_Protected_Object (Etype (Comp))
658          then
659             Tsk :=
660               Make_Selected_Component (Loc,
661                 Prefix        => Duplicate_Subexpr_No_Checks (Obj),
662                 Selector_Name => New_Occurrence_Of (Comp, Loc));
663             Set_Etype (Tsk, Etype (Comp));
664
665             if Is_Task_Type (Etype (Comp)) then
666                Append_To (Stmts, Cleanup_Task (N, Tsk));
667
668             elsif Is_Simple_Protected_Type (Etype (Comp)) then
669                Append_To (Stmts, Cleanup_Protected_Object (N, Tsk));
670
671             elsif Is_Record_Type (Etype (Comp)) then
672
673                --  Recurse, by generating the prefix of the argument to
674                --  the eventual cleanup call.
675
676                Append_List_To
677                  (Stmts, Cleanup_Record (N, Tsk, Etype (Comp)));
678
679             elsif Is_Array_Type (Etype (Comp)) then
680                Append_List_To
681                  (Stmts, Cleanup_Array (N, Tsk, Etype (Comp)));
682             end if;
683          end if;
684
685          Next_Component (Comp);
686       end loop;
687
688       return Stmts;
689    end Cleanup_Record;
690
691    ------------------------------
692    -- Cleanup_Protected_Object --
693    ------------------------------
694
695    function Cleanup_Protected_Object
696      (N   : Node_Id;
697       Ref : Node_Id) return Node_Id
698    is
699       Loc : constant Source_Ptr := Sloc (N);
700
701    begin
702       return
703         Make_Procedure_Call_Statement (Loc,
704           Name => New_Reference_To (RTE (RE_Finalize_Protection), Loc),
705           Parameter_Associations => New_List (
706             Concurrent_Ref (Ref)));
707    end Cleanup_Protected_Object;
708
709    ------------------------------------
710    -- Clean_Simple_Protected_Objects --
711    ------------------------------------
712
713    procedure Clean_Simple_Protected_Objects (N : Node_Id) is
714       Stmts : constant List_Id := Statements (Handled_Statement_Sequence (N));
715       Stmt  : Node_Id          := Last (Stmts);
716       E     : Entity_Id;
717
718    begin
719       E := First_Entity (Current_Scope);
720       while Present (E) loop
721          if (Ekind (E) = E_Variable
722               or else Ekind (E) = E_Constant)
723            and then Has_Simple_Protected_Object (Etype (E))
724            and then not Has_Task (Etype (E))
725            and then Nkind (Parent (E)) /= N_Object_Renaming_Declaration
726          then
727             declare
728                Typ : constant Entity_Id := Etype (E);
729                Ref : constant Node_Id := New_Occurrence_Of (E, Sloc (Stmt));
730
731             begin
732                if Is_Simple_Protected_Type (Typ) then
733                   Append_To (Stmts, Cleanup_Protected_Object (N, Ref));
734
735                elsif Has_Simple_Protected_Object (Typ) then
736                   if Is_Record_Type (Typ) then
737                      Append_List_To (Stmts, Cleanup_Record (N, Ref, Typ));
738
739                   elsif Is_Array_Type (Typ) then
740                      Append_List_To (Stmts, Cleanup_Array (N, Ref, Typ));
741                   end if;
742                end if;
743             end;
744          end if;
745
746          Next_Entity (E);
747       end loop;
748
749       --   Analyze inserted cleanup statements
750
751       if Present (Stmt) then
752          Stmt := Next (Stmt);
753
754          while Present (Stmt) loop
755             Analyze (Stmt);
756             Next (Stmt);
757          end loop;
758       end if;
759    end Clean_Simple_Protected_Objects;
760
761    ------------------
762    -- Cleanup_Task --
763    ------------------
764
765    function Cleanup_Task
766      (N   : Node_Id;
767       Ref : Node_Id) return Node_Id
768    is
769       Loc  : constant Source_Ptr := Sloc (N);
770    begin
771       return
772         Make_Procedure_Call_Statement (Loc,
773           Name => New_Reference_To (RTE (RE_Free_Task), Loc),
774           Parameter_Associations =>
775             New_List (Concurrent_Ref (Ref)));
776    end Cleanup_Task;
777
778    ---------------------------------
779    -- Has_Simple_Protected_Object --
780    ---------------------------------
781
782    function Has_Simple_Protected_Object (T : Entity_Id) return Boolean is
783       Comp : Entity_Id;
784
785    begin
786       if Is_Simple_Protected_Type (T) then
787          return True;
788
789       elsif Is_Array_Type (T) then
790          return Has_Simple_Protected_Object (Component_Type (T));
791
792       elsif Is_Record_Type (T) then
793          Comp := First_Component (T);
794
795          while Present (Comp) loop
796             if Has_Simple_Protected_Object (Etype (Comp)) then
797                return True;
798             end if;
799
800             Next_Component (Comp);
801          end loop;
802
803          return False;
804
805       else
806          return False;
807       end if;
808    end Has_Simple_Protected_Object;
809
810    ------------------------------
811    -- Is_Simple_Protected_Type --
812    ------------------------------
813
814    function Is_Simple_Protected_Type (T : Entity_Id) return Boolean is
815    begin
816       return Is_Protected_Type (T) and then not Has_Entries (T);
817    end Is_Simple_Protected_Type;
818
819    ------------------------------
820    -- Check_Visibly_Controlled --
821    ------------------------------
822
823    procedure Check_Visibly_Controlled
824      (Prim : Final_Primitives;
825       Typ  : Entity_Id;
826       E    : in out Entity_Id;
827       Cref : in out Node_Id)
828    is
829       Parent_Type : Entity_Id;
830       Op          : Entity_Id;
831
832    begin
833       if Is_Derived_Type (Typ)
834         and then Comes_From_Source (E)
835         and then not Is_Overriding_Operation (E)
836       then
837          --  We know that the explicit operation on the type does not override
838          --  the inherited operation of the parent, and that the derivation
839          --  is from a private type that is not visibly controlled.
840
841          Parent_Type := Etype (Typ);
842          Op := Find_Prim_Op (Parent_Type, Name_Of (Prim));
843
844          if Present (Op) then
845             E := Op;
846
847             --  Wrap the object to be initialized into the proper
848             --  unchecked conversion, to be compatible with the operation
849             --  to be called.
850
851             if Nkind (Cref) = N_Unchecked_Type_Conversion then
852                Cref := Unchecked_Convert_To (Parent_Type, Expression (Cref));
853             else
854                Cref := Unchecked_Convert_To (Parent_Type, Cref);
855             end if;
856          end if;
857       end if;
858    end Check_Visibly_Controlled;
859
860    -------------------------------
861    -- CW_Or_Has_Controlled_Part --
862    -------------------------------
863
864    function CW_Or_Has_Controlled_Part (T : Entity_Id) return Boolean is
865    begin
866       return Is_Class_Wide_Type (T) or else Needs_Finalization (T);
867    end CW_Or_Has_Controlled_Part;
868
869    --------------------------
870    -- Controller_Component --
871    --------------------------
872
873    function Controller_Component (Typ : Entity_Id) return Entity_Id is
874       T         : Entity_Id := Base_Type (Typ);
875       Comp      : Entity_Id;
876       Comp_Scop : Entity_Id;
877       Res       : Entity_Id := Empty;
878       Res_Scop  : Entity_Id := Empty;
879
880    begin
881       if Is_Class_Wide_Type (T) then
882          T := Root_Type (T);
883       end if;
884
885       if Is_Private_Type (T) then
886          T := Underlying_Type (T);
887       end if;
888
889       --  Fetch the outermost controller
890
891       Comp := First_Entity (T);
892       while Present (Comp) loop
893          if Chars (Comp) = Name_uController then
894             Comp_Scop := Scope (Original_Record_Component (Comp));
895
896             --  If this controller is at the outermost level, no need to
897             --  look for another one
898
899             if Comp_Scop = T then
900                return Comp;
901
902             --  Otherwise record the outermost one and continue looking
903
904             elsif Res = Empty or else Is_Ancestor (Res_Scop, Comp_Scop) then
905                Res      := Comp;
906                Res_Scop := Comp_Scop;
907             end if;
908          end if;
909
910          Next_Entity (Comp);
911       end loop;
912
913       --  If we fall through the loop, there is no controller component
914
915       return Res;
916    end Controller_Component;
917
918    ------------------
919    -- Convert_View --
920    ------------------
921
922    function Convert_View
923      (Proc : Entity_Id;
924       Arg  : Node_Id;
925       Ind  : Pos := 1) return Node_Id
926    is
927       Fent : Entity_Id := First_Entity (Proc);
928       Ftyp : Entity_Id;
929       Atyp : Entity_Id;
930
931    begin
932       for J in 2 .. Ind loop
933          Next_Entity (Fent);
934       end loop;
935
936       Ftyp := Etype (Fent);
937
938       if Nkind_In (Arg, N_Type_Conversion, N_Unchecked_Type_Conversion) then
939          Atyp := Entity (Subtype_Mark (Arg));
940       else
941          Atyp := Etype (Arg);
942       end if;
943
944       if Is_Abstract_Subprogram (Proc) and then Is_Tagged_Type (Ftyp) then
945          return Unchecked_Convert_To (Class_Wide_Type (Ftyp), Arg);
946
947       elsif Ftyp /= Atyp
948         and then Present (Atyp)
949         and then
950           (Is_Private_Type (Ftyp) or else Is_Private_Type (Atyp))
951         and then
952            Base_Type (Underlying_Type (Atyp)) =
953              Base_Type (Underlying_Type (Ftyp))
954       then
955          return Unchecked_Convert_To (Ftyp, Arg);
956
957       --  If the argument is already a conversion, as generated by
958       --  Make_Init_Call, set the target type to the type of the formal
959       --  directly, to avoid spurious typing problems.
960
961       elsif Nkind_In (Arg, N_Unchecked_Type_Conversion, N_Type_Conversion)
962         and then not Is_Class_Wide_Type (Atyp)
963       then
964          Set_Subtype_Mark (Arg, New_Occurrence_Of (Ftyp, Sloc (Arg)));
965          Set_Etype (Arg, Ftyp);
966          return Arg;
967
968       else
969          return Arg;
970       end if;
971    end Convert_View;
972
973    -------------------------------
974    -- Establish_Transient_Scope --
975    -------------------------------
976
977    --  This procedure is called each time a transient block has to be inserted
978    --  that is to say for each call to a function with unconstrained or tagged
979    --  result. It creates a new scope on the stack scope in order to enclose
980    --  all transient variables generated
981
982    procedure Establish_Transient_Scope (N : Node_Id; Sec_Stack : Boolean) is
983       Loc       : constant Source_Ptr := Sloc (N);
984       Wrap_Node : Node_Id;
985
986    begin
987       --  Nothing to do for virtual machines where memory is GCed
988
989       if VM_Target /= No_VM then
990          return;
991       end if;
992
993       --  Do not create a transient scope if we are already inside one
994
995       for S in reverse Scope_Stack.First .. Scope_Stack.Last loop
996          if Scope_Stack.Table (S).Is_Transient then
997             if Sec_Stack then
998                Set_Uses_Sec_Stack (Scope_Stack.Table (S).Entity);
999             end if;
1000
1001             return;
1002
1003          --  If we have encountered Standard there are no enclosing
1004          --  transient scopes.
1005
1006          elsif Scope_Stack.Table (S).Entity = Standard_Standard then
1007             exit;
1008
1009          end if;
1010       end loop;
1011
1012       Wrap_Node := Find_Node_To_Be_Wrapped (N);
1013
1014       --  Case of no wrap node, false alert, no transient scope needed
1015
1016       if No (Wrap_Node) then
1017          null;
1018
1019       --  If the node to wrap is an iteration_scheme, the expression is
1020       --  one of the bounds, and the expansion will make an explicit
1021       --  declaration for it (see Analyze_Iteration_Scheme, sem_ch5.adb),
1022       --  so do not apply any transformations here.
1023
1024       elsif Nkind (Wrap_Node) = N_Iteration_Scheme then
1025          null;
1026
1027       else
1028          Push_Scope (New_Internal_Entity (E_Block, Current_Scope, Loc, 'B'));
1029          Set_Scope_Is_Transient;
1030
1031          if Sec_Stack then
1032             Set_Uses_Sec_Stack (Current_Scope);
1033             Check_Restriction (No_Secondary_Stack, N);
1034          end if;
1035
1036          Set_Etype (Current_Scope, Standard_Void_Type);
1037          Set_Node_To_Be_Wrapped (Wrap_Node);
1038
1039          if Debug_Flag_W then
1040             Write_Str ("    <Transient>");
1041             Write_Eol;
1042          end if;
1043       end if;
1044    end Establish_Transient_Scope;
1045
1046    ----------------------------
1047    -- Expand_Cleanup_Actions --
1048    ----------------------------
1049
1050    procedure Expand_Cleanup_Actions (N : Node_Id) is
1051       S       : constant Entity_Id  := Current_Scope;
1052       Flist   : constant Entity_Id := Finalization_Chain_Entity (S);
1053       Is_Task : constant Boolean := Nkind (Original_Node (N)) = N_Task_Body;
1054
1055       Is_Master            : constant Boolean :=
1056                                Nkind (N) /= N_Entry_Body
1057                                  and then Is_Task_Master (N);
1058       Is_Protected         : constant Boolean :=
1059                                Nkind (N) = N_Subprogram_Body
1060                                  and then Is_Protected_Subprogram_Body (N);
1061       Is_Task_Allocation   : constant Boolean :=
1062                                Nkind (N) = N_Block_Statement
1063                                  and then Is_Task_Allocation_Block (N);
1064       Is_Asynchronous_Call : constant Boolean :=
1065                                Nkind (N) = N_Block_Statement
1066                                  and then Is_Asynchronous_Call_Block (N);
1067
1068       Previous_At_End_Proc : constant Node_Id :=
1069                                At_End_Proc (Handled_Statement_Sequence (N));
1070
1071       Clean     : Entity_Id;
1072       Loc       : Source_Ptr;
1073       Mark      : Entity_Id := Empty;
1074       New_Decls : constant List_Id := New_List;
1075       Blok      : Node_Id;
1076       End_Lab   : Node_Id;
1077       Wrapped   : Boolean;
1078       Chain     : Entity_Id := Empty;
1079       Decl      : Node_Id;
1080       Old_Poll  : Boolean;
1081
1082    begin
1083       --  If we are generating expanded code for debugging purposes, use
1084       --  the Sloc of the point of insertion for the cleanup code. The Sloc
1085       --  will be updated subsequently to reference the proper line in the
1086       --  .dg file.  If we are not debugging generated code, use instead
1087       --  No_Location, so that no debug information is generated for the
1088       --  cleanup code. This makes the behavior of the NEXT command in GDB
1089       --  monotonic, and makes the placement of breakpoints more accurate.
1090
1091       if Debug_Generated_Code then
1092          Loc := Sloc (S);
1093       else
1094          Loc := No_Location;
1095       end if;
1096
1097       --  There are cleanup actions only if the secondary stack needs
1098       --  releasing or some finalizations are needed or in the context
1099       --  of tasking
1100
1101       if Uses_Sec_Stack (Current_Scope)
1102         and then not Sec_Stack_Needed_For_Return (Current_Scope)
1103       then
1104          null;
1105       elsif No (Flist)
1106         and then not Is_Master
1107         and then not Is_Task
1108         and then not Is_Protected
1109         and then not Is_Task_Allocation
1110         and then not Is_Asynchronous_Call
1111       then
1112          Clean_Simple_Protected_Objects (N);
1113          return;
1114       end if;
1115
1116       --  If the current scope is the subprogram body that is the rewriting
1117       --  of a task body, and the descriptors have not been delayed (due to
1118       --  some nested instantiations) do not generate redundant cleanup
1119       --  actions: the cleanup procedure already exists for this body.
1120
1121       if Nkind (N) = N_Subprogram_Body
1122         and then Nkind (Original_Node (N)) = N_Task_Body
1123         and then not Delay_Subprogram_Descriptors (Corresponding_Spec (N))
1124       then
1125          return;
1126       end if;
1127
1128       --  Set polling off, since we don't need to poll during cleanup
1129       --  actions, and indeed for the cleanup routine, which is executed
1130       --  with aborts deferred, we don't want polling.
1131
1132       Old_Poll := Polling_Required;
1133       Polling_Required := False;
1134
1135       --  Make sure we have a declaration list, since we will add to it
1136
1137       if No (Declarations (N)) then
1138          Set_Declarations (N, New_List);
1139       end if;
1140
1141       --  The task activation call has already been built for task
1142       --  allocation blocks.
1143
1144       if not Is_Task_Allocation then
1145          Build_Task_Activation_Call (N);
1146       end if;
1147
1148       if Is_Master then
1149          Establish_Task_Master (N);
1150       end if;
1151
1152       --  If secondary stack is in use, expand:
1153       --    _Mxx : constant Mark_Id := SS_Mark;
1154
1155       --  Suppress calls to SS_Mark and SS_Release if VM_Target,
1156       --  since we never use the secondary stack on the VM.
1157
1158       if Uses_Sec_Stack (Current_Scope)
1159         and then not Sec_Stack_Needed_For_Return (Current_Scope)
1160         and then VM_Target = No_VM
1161       then
1162          Mark := Make_Temporary (Loc, 'M');
1163          Append_To (New_Decls,
1164            Make_Object_Declaration (Loc,
1165              Defining_Identifier => Mark,
1166              Object_Definition   => New_Reference_To (RTE (RE_Mark_Id), Loc),
1167              Expression =>
1168                Make_Function_Call (Loc,
1169                  Name => New_Reference_To (RTE (RE_SS_Mark), Loc))));
1170
1171          Set_Uses_Sec_Stack (Current_Scope, False);
1172       end if;
1173
1174       --  If finalization list is present then expand:
1175       --   Local_Final_List : System.FI.Finalizable_Ptr;
1176
1177       if Present (Flist) then
1178          Append_To (New_Decls,
1179            Make_Object_Declaration (Loc,
1180              Defining_Identifier => Flist,
1181              Object_Definition   =>
1182                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
1183       end if;
1184
1185       --  Clean-up procedure definition
1186
1187       Clean := Make_Defining_Identifier (Loc, Name_uClean);
1188       Set_Suppress_Elaboration_Warnings (Clean);
1189       Append_To (New_Decls,
1190         Make_Clean (N, Clean, Mark, Flist,
1191           Is_Task,
1192           Is_Master,
1193           Is_Protected,
1194           Is_Task_Allocation,
1195           Is_Asynchronous_Call,
1196           Previous_At_End_Proc));
1197
1198       --  The previous AT END procedure, if any, has been captured in Clean:
1199       --  reset it to Empty now because we check further on that we never
1200       --  overwrite an existing AT END call.
1201
1202       Set_At_End_Proc (Handled_Statement_Sequence (N), Empty);
1203
1204       --  If exception handlers are present, wrap the Sequence of statements in
1205       --  a block because it is not possible to get exception handlers and an
1206       --  AT END call in the same scope.
1207
1208       if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then
1209
1210          --  Preserve end label to provide proper cross-reference information
1211
1212          End_Lab := End_Label (Handled_Statement_Sequence (N));
1213          Blok :=
1214            Make_Block_Statement (Loc,
1215              Handled_Statement_Sequence => Handled_Statement_Sequence (N));
1216          Set_Handled_Statement_Sequence (N,
1217            Make_Handled_Sequence_Of_Statements (Loc, New_List (Blok)));
1218          Set_End_Label (Handled_Statement_Sequence (N), End_Lab);
1219          Wrapped := True;
1220
1221          --  Comment needed here, see RH for 1.306 ???
1222
1223          if Nkind (N) = N_Subprogram_Body then
1224             Set_Has_Nested_Block_With_Handler (Current_Scope);
1225          end if;
1226
1227       --  Otherwise we do not wrap
1228
1229       else
1230          Wrapped := False;
1231          Blok    := Empty;
1232       end if;
1233
1234       --  Don't move the _chain Activation_Chain declaration in task
1235       --  allocation blocks. Task allocation blocks use this object
1236       --  in their cleanup handlers, and gigi complains if it is declared
1237       --  in the sequence of statements of the scope that declares the
1238       --  handler.
1239
1240       if Is_Task_Allocation then
1241          Chain := Activation_Chain_Entity (N);
1242
1243          Decl := First (Declarations (N));
1244          while Nkind (Decl) /= N_Object_Declaration
1245            or else Defining_Identifier (Decl) /= Chain
1246          loop
1247             Next (Decl);
1248             pragma Assert (Present (Decl));
1249          end loop;
1250
1251          Remove (Decl);
1252          Prepend_To (New_Decls, Decl);
1253       end if;
1254
1255       --  Now we move the declarations into the Sequence of statements
1256       --  in order to get them protected by the AT END call. It may seem
1257       --  weird to put declarations in the sequence of statement but in
1258       --  fact nothing forbids that at the tree level. We also set the
1259       --  First_Real_Statement field so that we remember where the real
1260       --  statements (i.e. original statements) begin. Note that if we
1261       --  wrapped the statements, the first real statement is inside the
1262       --  inner block. If the First_Real_Statement is already set (as is
1263       --  the case for subprogram bodies that are expansions of task bodies)
1264       --  then do not reset it, because its declarative part would migrate
1265       --  to the statement part.
1266
1267       if not Wrapped then
1268          if No (First_Real_Statement (Handled_Statement_Sequence (N))) then
1269             Set_First_Real_Statement (Handled_Statement_Sequence (N),
1270               First (Statements (Handled_Statement_Sequence (N))));
1271          end if;
1272
1273       else
1274          Set_First_Real_Statement (Handled_Statement_Sequence (N), Blok);
1275       end if;
1276
1277       Append_List_To (Declarations (N),
1278         Statements (Handled_Statement_Sequence (N)));
1279       Set_Statements (Handled_Statement_Sequence (N), Declarations (N));
1280
1281       --  We need to reset the Sloc of the handled statement sequence to
1282       --  properly reflect the new initial "statement" in the sequence.
1283
1284       Set_Sloc
1285         (Handled_Statement_Sequence (N), Sloc (First (Declarations (N))));
1286
1287       --  The declarations of the _Clean procedure and finalization chain
1288       --  replace the old declarations that have been moved inward.
1289
1290       Set_Declarations (N, New_Decls);
1291       Analyze_Declarations (New_Decls);
1292
1293       --  The At_End call is attached to the sequence of statements
1294
1295       declare
1296          HSS : Node_Id;
1297
1298       begin
1299          --  If the construct is a protected subprogram, then the call to
1300          --  the corresponding unprotected subprogram appears in a block which
1301          --  is the last statement in the body, and it is this block that must
1302          --  be covered by the At_End handler.
1303
1304          if Is_Protected then
1305             HSS := Handled_Statement_Sequence
1306               (Last (Statements (Handled_Statement_Sequence (N))));
1307          else
1308             HSS := Handled_Statement_Sequence (N);
1309          end if;
1310
1311          --  Never overwrite an existing AT END call
1312
1313          pragma Assert (No (At_End_Proc (HSS)));
1314
1315          Set_At_End_Proc (HSS, New_Occurrence_Of (Clean, Loc));
1316          Expand_At_End_Handler (HSS, Empty);
1317       end;
1318
1319       --  Restore saved polling mode
1320
1321       Polling_Required := Old_Poll;
1322    end Expand_Cleanup_Actions;
1323
1324    -------------------------------
1325    -- Expand_Ctrl_Function_Call --
1326    -------------------------------
1327
1328    procedure Expand_Ctrl_Function_Call (N : Node_Id) is
1329       Loc     : constant Source_Ptr := Sloc (N);
1330       Rtype   : constant Entity_Id  := Etype (N);
1331       Utype   : constant Entity_Id  := Underlying_Type (Rtype);
1332       Ref     : Node_Id;
1333       Action  : Node_Id;
1334       Action2 : Node_Id := Empty;
1335
1336       Attach_Level : Uint    := Uint_1;
1337       Len_Ref      : Node_Id := Empty;
1338
1339       function Last_Array_Component
1340         (Ref : Node_Id;
1341          Typ : Entity_Id) return Node_Id;
1342       --  Creates a reference to the last component of the array object
1343       --  designated by Ref whose type is Typ.
1344
1345       --------------------------
1346       -- Last_Array_Component --
1347       --------------------------
1348
1349       function Last_Array_Component
1350         (Ref : Node_Id;
1351          Typ : Entity_Id) return Node_Id
1352       is
1353          Index_List : constant List_Id := New_List;
1354
1355       begin
1356          for N in 1 .. Number_Dimensions (Typ) loop
1357             Append_To (Index_List,
1358               Make_Attribute_Reference (Loc,
1359                 Prefix         => Duplicate_Subexpr_No_Checks (Ref),
1360                 Attribute_Name => Name_Last,
1361                 Expressions    => New_List (
1362                   Make_Integer_Literal (Loc, N))));
1363          end loop;
1364
1365          return
1366            Make_Indexed_Component (Loc,
1367              Prefix      => Duplicate_Subexpr (Ref),
1368              Expressions => Index_List);
1369       end Last_Array_Component;
1370
1371    --  Start of processing for Expand_Ctrl_Function_Call
1372
1373    begin
1374       --  Optimization, if the returned value (which is on the sec-stack) is
1375       --  returned again, no need to copy/readjust/finalize, we can just pass
1376       --  the value thru (see Expand_N_Simple_Return_Statement), and thus no
1377       --  attachment is needed
1378
1379       if Nkind (Parent (N)) = N_Simple_Return_Statement then
1380          return;
1381       end if;
1382
1383       --  Resolution is now finished, make sure we don't start analysis again
1384       --  because of the duplication.
1385
1386       Set_Analyzed (N);
1387       Ref := Duplicate_Subexpr_No_Checks (N);
1388
1389       --  Now we can generate the Attach Call. Note that this value is always
1390       --  on the (secondary) stack and thus is attached to a singly linked
1391       --  final list:
1392
1393       --    Resx := F (X)'reference;
1394       --    Attach_To_Final_List (_Lx, Resx.all, 1);
1395
1396       --  or when there are controlled components:
1397
1398       --    Attach_To_Final_List (_Lx, Resx._controller, 1);
1399
1400       --  or when it is both Is_Controlled and Has_Controlled_Components:
1401
1402       --    Attach_To_Final_List (_Lx, Resx._controller, 1);
1403       --    Attach_To_Final_List (_Lx, Resx, 1);
1404
1405       --  or if it is an array with Is_Controlled (and Has_Controlled)
1406
1407       --    Attach_To_Final_List (_Lx, Resx (Resx'last), 3);
1408
1409       --    An attach level of 3 means that a whole array is to be attached to
1410       --    the finalization list (including the controlled components).
1411
1412       --  or if it is an array with Has_Controlled_Components but not
1413       --  Is_Controlled:
1414
1415       --    Attach_To_Final_List (_Lx, Resx (Resx'last)._controller, 3);
1416
1417       --  Case where type has controlled components
1418
1419       if Has_Controlled_Component (Rtype) then
1420          declare
1421             T1 : Entity_Id := Rtype;
1422             T2 : Entity_Id := Utype;
1423
1424          begin
1425             if Is_Array_Type (T2) then
1426                Len_Ref :=
1427                  Make_Attribute_Reference (Loc,
1428                    Prefix =>
1429                      Duplicate_Subexpr_Move_Checks
1430                        (Unchecked_Convert_To (T2, Ref)),
1431                    Attribute_Name => Name_Length);
1432             end if;
1433
1434             while Is_Array_Type (T2) loop
1435                if T1 /= T2 then
1436                   Ref := Unchecked_Convert_To (T2, Ref);
1437                end if;
1438
1439                Ref := Last_Array_Component (Ref, T2);
1440                Attach_Level := Uint_3;
1441                T1 := Component_Type (T2);
1442                T2 := Underlying_Type (T1);
1443             end loop;
1444
1445             --  If the type has controlled components, go to the controller
1446             --  except in the case of arrays of controlled objects since in
1447             --  this case objects and their components are already chained
1448             --  and the head of the chain is the last array element.
1449
1450             if Is_Array_Type (Rtype) and then Is_Controlled (T2) then
1451                null;
1452
1453             elsif Has_Controlled_Component (T2) then
1454                if T1 /= T2 then
1455                   Ref := Unchecked_Convert_To (T2, Ref);
1456                end if;
1457
1458                Ref :=
1459                  Make_Selected_Component (Loc,
1460                    Prefix        => Ref,
1461                    Selector_Name => Make_Identifier (Loc, Name_uController));
1462             end if;
1463          end;
1464
1465          --  Here we know that 'Ref' has a controller so we may as well attach
1466          --  it directly.
1467
1468          Action :=
1469            Make_Attach_Call (
1470              Obj_Ref      => Ref,
1471              Flist_Ref    => Find_Final_List (Current_Scope),
1472              With_Attach  => Make_Integer_Literal (Loc, Attach_Level));
1473
1474          --  If it is also Is_Controlled we need to attach the global object
1475
1476          if Is_Controlled (Rtype) then
1477             Action2 :=
1478               Make_Attach_Call (
1479                 Obj_Ref      => Duplicate_Subexpr_No_Checks (N),
1480                 Flist_Ref    => Find_Final_List (Current_Scope),
1481                 With_Attach  => Make_Integer_Literal (Loc, Attach_Level));
1482          end if;
1483
1484       --  Here, we have a controlled type that does not seem to have controlled
1485       --  components but it could be a class wide type whose further
1486       --  derivations have controlled components. So we don't know if the
1487       --  object itself needs to be attached or if it has a record controller.
1488       --  We need to call a runtime function (Deep_Tag_Attach) which knows what
1489       --  to do thanks to the RC_Offset in the dispatch table.
1490
1491       else
1492          Action :=
1493            Make_Procedure_Call_Statement (Loc,
1494              Name => New_Reference_To (RTE (RE_Deep_Tag_Attach), Loc),
1495              Parameter_Associations => New_List (
1496                Find_Final_List (Current_Scope),
1497
1498                Make_Attribute_Reference (Loc,
1499                    Prefix => Ref,
1500                    Attribute_Name => Name_Address),
1501
1502                Make_Integer_Literal (Loc, Attach_Level)));
1503       end if;
1504
1505       if Present (Len_Ref) then
1506          Action :=
1507            Make_Implicit_If_Statement (N,
1508              Condition => Make_Op_Gt (Loc,
1509                Left_Opnd  => Len_Ref,
1510                Right_Opnd => Make_Integer_Literal (Loc, 0)),
1511              Then_Statements => New_List (Action));
1512       end if;
1513
1514       Insert_Action (N, Action);
1515       if Present (Action2) then
1516          Insert_Action (N, Action2);
1517       end if;
1518    end Expand_Ctrl_Function_Call;
1519
1520    ---------------------------
1521    -- Expand_N_Package_Body --
1522    ---------------------------
1523
1524    --  Add call to Activate_Tasks if body is an activator (actual processing
1525    --  is in chapter 9).
1526
1527    --  Generate subprogram descriptor for elaboration routine
1528
1529    --  Encode entity names in package body
1530
1531    procedure Expand_N_Package_Body (N : Node_Id) is
1532       Ent : constant Entity_Id := Corresponding_Spec (N);
1533
1534    begin
1535       --  This is done only for non-generic packages
1536
1537       if Ekind (Ent) = E_Package then
1538          Push_Scope (Corresponding_Spec (N));
1539
1540          --  Build dispatch tables of library level tagged types
1541
1542          if Is_Library_Level_Entity (Ent) then
1543             Build_Static_Dispatch_Tables (N);
1544          end if;
1545
1546          Build_Task_Activation_Call (N);
1547          Pop_Scope;
1548       end if;
1549
1550       Set_Elaboration_Flag (N, Corresponding_Spec (N));
1551       Set_In_Package_Body (Ent, False);
1552
1553       --  Set to encode entity names in package body before gigi is called
1554
1555       Qualify_Entity_Names (N);
1556    end Expand_N_Package_Body;
1557
1558    ----------------------------------
1559    -- Expand_N_Package_Declaration --
1560    ----------------------------------
1561
1562    --  Add call to Activate_Tasks if there are tasks declared and the package
1563    --  has no body. Note that in Ada83, this may result in premature activation
1564    --  of some tasks, given that we cannot tell whether a body will eventually
1565    --  appear.
1566
1567    procedure Expand_N_Package_Declaration (N : Node_Id) is
1568       Spec    : constant Node_Id   := Specification (N);
1569       Id      : constant Entity_Id := Defining_Entity (N);
1570       Decls   : List_Id;
1571       No_Body : Boolean := False;
1572       --  True in the case of a package declaration that is a compilation unit
1573       --  and for which no associated body will be compiled in
1574       --  this compilation.
1575
1576    begin
1577       --  Case of a package declaration other than a compilation unit
1578
1579       if Nkind (Parent (N)) /= N_Compilation_Unit then
1580          null;
1581
1582       --  Case of a compilation unit that does not require a body
1583
1584       elsif not Body_Required (Parent (N))
1585         and then not Unit_Requires_Body (Id)
1586       then
1587          No_Body := True;
1588
1589       --  Special case of generating calling stubs for a remote call interface
1590       --  package: even though the package declaration requires one, the
1591       --  body won't be processed in this compilation (so any stubs for RACWs
1592       --  declared in the package must be generated here, along with the
1593       --  spec).
1594
1595       elsif Parent (N) = Cunit (Main_Unit)
1596         and then Is_Remote_Call_Interface (Id)
1597         and then Distribution_Stub_Mode = Generate_Caller_Stub_Body
1598       then
1599          No_Body := True;
1600       end if;
1601
1602       --  For a package declaration that implies no associated body, generate
1603       --  task activation call and RACW supporting bodies now (since we won't
1604       --  have a specific separate compilation unit for that).
1605
1606       if No_Body then
1607          Push_Scope (Id);
1608
1609          if Has_RACW (Id) then
1610
1611             --  Generate RACW subprogram bodies
1612
1613             Decls := Private_Declarations (Spec);
1614
1615             if No (Decls) then
1616                Decls := Visible_Declarations (Spec);
1617             end if;
1618
1619             if No (Decls) then
1620                Decls := New_List;
1621                Set_Visible_Declarations (Spec, Decls);
1622             end if;
1623
1624             Append_RACW_Bodies (Decls, Id);
1625             Analyze_List (Decls);
1626          end if;
1627
1628          if Present (Activation_Chain_Entity (N)) then
1629
1630             --  Generate task activation call as last step of elaboration
1631
1632             Build_Task_Activation_Call (N);
1633          end if;
1634
1635          Pop_Scope;
1636       end if;
1637
1638       --  Build dispatch tables of library level tagged types
1639
1640       if Is_Compilation_Unit (Id)
1641         or else (Is_Generic_Instance (Id)
1642                    and then Is_Library_Level_Entity (Id))
1643       then
1644          Build_Static_Dispatch_Tables (N);
1645       end if;
1646
1647       --  Note: it is not necessary to worry about generating a subprogram
1648       --  descriptor, since the only way to get exception handlers into a
1649       --  package spec is to include instantiations, and that would cause
1650       --  generation of subprogram descriptors to be delayed in any case.
1651
1652       --  Set to encode entity names in package spec before gigi is called
1653
1654       Qualify_Entity_Names (N);
1655    end Expand_N_Package_Declaration;
1656
1657    ---------------------
1658    -- Find_Final_List --
1659    ---------------------
1660
1661    function Find_Final_List
1662      (E   : Entity_Id;
1663       Ref : Node_Id := Empty) return Node_Id
1664    is
1665       Loc : constant Source_Ptr := Sloc (Ref);
1666       S   : Entity_Id;
1667       Id  : Entity_Id;
1668       R   : Node_Id;
1669
1670    begin
1671       --  If the restriction No_Finalization applies, then there's not any
1672       --  finalization list available to return, so return Empty.
1673
1674       if Restriction_Active (No_Finalization) then
1675          return Empty;
1676
1677       --  Case of an internal component. The Final list is the record
1678       --  controller of the enclosing record.
1679
1680       elsif Present (Ref) then
1681          R := Ref;
1682          loop
1683             case Nkind (R) is
1684                when N_Unchecked_Type_Conversion | N_Type_Conversion =>
1685                   R := Expression (R);
1686
1687                when N_Indexed_Component | N_Explicit_Dereference =>
1688                   R := Prefix (R);
1689
1690                when  N_Selected_Component =>
1691                   R := Prefix (R);
1692                   exit;
1693
1694                when  N_Identifier =>
1695                   exit;
1696
1697                when others =>
1698                   raise Program_Error;
1699             end case;
1700          end loop;
1701
1702          return
1703            Make_Selected_Component (Loc,
1704              Prefix =>
1705                Make_Selected_Component (Loc,
1706                  Prefix        => R,
1707                  Selector_Name => Make_Identifier (Loc, Name_uController)),
1708              Selector_Name => Make_Identifier (Loc, Name_F));
1709
1710       --  Case of a dynamically allocated object whose access type has an
1711       --  Associated_Final_Chain. The final list is the corresponding list
1712       --  controller (the next entity in the scope of the access type with
1713       --  the right type). If the type comes from a With_Type clause, no
1714       --  controller was created, we use the global chain instead. (The code
1715       --  related to with_type clauses should presumably be removed at some
1716       --  point since that feature is obsolete???)
1717
1718       --  An anonymous access type either has a list created for it when the
1719       --  allocator is a for an access parameter or an access discriminant,
1720       --  or else it uses the list of the enclosing dynamic scope, when the
1721       --  context is a declaration or an assignment.
1722
1723       elsif Is_Access_Type (E)
1724         and then (Present (Associated_Final_Chain (E))
1725                    or else From_With_Type (E))
1726       then
1727          if From_With_Type (E) then
1728             return New_Reference_To (RTE (RE_Global_Final_List), Sloc (E));
1729
1730          --  Use the access type's associated finalization chain
1731
1732          else
1733             return
1734               Make_Selected_Component (Loc,
1735                 Prefix        =>
1736                   New_Reference_To
1737                     (Associated_Final_Chain (Base_Type (E)), Loc),
1738                 Selector_Name => Make_Identifier (Loc, Name_F));
1739          end if;
1740
1741       else
1742          S := Nearest_Dynamic_Scope (E);
1743
1744          --  When the finalization chain entity is 'Error', it means that there
1745          --  should not be any chain at that level and that the enclosing one
1746          --  should be used.
1747
1748          --  This is a nasty kludge, see ??? note in exp_ch11
1749
1750          while Finalization_Chain_Entity (S) = Error loop
1751             S := Enclosing_Dynamic_Scope (S);
1752          end loop;
1753
1754          if S = Standard_Standard then
1755             return New_Reference_To (RTE (RE_Global_Final_List), Sloc (E));
1756          else
1757             if No (Finalization_Chain_Entity (S)) then
1758
1759                --  In the case where the scope is a subprogram, retrieve the
1760                --  Sloc of subprogram's body for association with the chain,
1761                --  since using the Sloc of the spec would be confusing during
1762                --  source-line stepping within the debugger.
1763
1764                declare
1765                   Flist_Loc : Source_Ptr := Sloc (S);
1766                   Subp_Body : Node_Id;
1767
1768                begin
1769                   if Ekind (S) in Subprogram_Kind then
1770                      Subp_Body := Unit_Declaration_Node (S);
1771
1772                      if Nkind (Subp_Body) /= N_Subprogram_Body then
1773                         Subp_Body := Corresponding_Body (Subp_Body);
1774                      end if;
1775
1776                      if Present (Subp_Body) then
1777                         Flist_Loc := Sloc (Subp_Body);
1778                      end if;
1779                   end if;
1780
1781                   Id := Make_Temporary (Flist_Loc, 'F');
1782                end;
1783
1784                Set_Finalization_Chain_Entity (S, Id);
1785
1786                --  Set momentarily some semantics attributes to allow normal
1787                --  analysis of expansions containing references to this chain.
1788                --  Will be fully decorated during the expansion of the scope
1789                --  itself.
1790
1791                Set_Ekind (Id, E_Variable);
1792                Set_Etype (Id, RTE (RE_Finalizable_Ptr));
1793             end if;
1794
1795             return New_Reference_To (Finalization_Chain_Entity (S), Sloc (E));
1796          end if;
1797       end if;
1798    end Find_Final_List;
1799
1800    -----------------------------
1801    -- Find_Node_To_Be_Wrapped --
1802    -----------------------------
1803
1804    function Find_Node_To_Be_Wrapped (N : Node_Id) return Node_Id is
1805       P          : Node_Id;
1806       The_Parent : Node_Id;
1807
1808    begin
1809       The_Parent := N;
1810       loop
1811          P := The_Parent;
1812          pragma Assert (P /= Empty);
1813          The_Parent := Parent (P);
1814
1815          case Nkind (The_Parent) is
1816
1817             --  Simple statement can be wrapped
1818
1819             when N_Pragma =>
1820                return The_Parent;
1821
1822             --  Usually assignments are good candidate for wrapping
1823             --  except when they have been generated as part of a
1824             --  controlled aggregate where the wrapping should take
1825             --  place more globally.
1826
1827             when N_Assignment_Statement =>
1828                if No_Ctrl_Actions (The_Parent) then
1829                   null;
1830                else
1831                   return The_Parent;
1832                end if;
1833
1834             --  An entry call statement is a special case if it occurs in
1835             --  the context of a Timed_Entry_Call. In this case we wrap
1836             --  the entire timed entry call.
1837
1838             when N_Entry_Call_Statement     |
1839                  N_Procedure_Call_Statement =>
1840                if Nkind (Parent (The_Parent)) = N_Entry_Call_Alternative
1841                  and then Nkind_In (Parent (Parent (The_Parent)),
1842                                     N_Timed_Entry_Call,
1843                                     N_Conditional_Entry_Call)
1844                then
1845                   return Parent (Parent (The_Parent));
1846                else
1847                   return The_Parent;
1848                end if;
1849
1850             --  Object declarations are also a boundary for the transient scope
1851             --  even if they are not really wrapped
1852             --  (see Wrap_Transient_Declaration)
1853
1854             when N_Object_Declaration          |
1855                  N_Object_Renaming_Declaration |
1856                  N_Subtype_Declaration         =>
1857                return The_Parent;
1858
1859             --  The expression itself is to be wrapped if its parent is a
1860             --  compound statement or any other statement where the expression
1861             --  is known to be scalar
1862
1863             when N_Accept_Alternative               |
1864                  N_Attribute_Definition_Clause      |
1865                  N_Case_Statement                   |
1866                  N_Code_Statement                   |
1867                  N_Delay_Alternative                |
1868                  N_Delay_Until_Statement            |
1869                  N_Delay_Relative_Statement         |
1870                  N_Discriminant_Association         |
1871                  N_Elsif_Part                       |
1872                  N_Entry_Body_Formal_Part           |
1873                  N_Exit_Statement                   |
1874                  N_If_Statement                     |
1875                  N_Iteration_Scheme                 |
1876                  N_Terminate_Alternative            =>
1877                return P;
1878
1879             when N_Attribute_Reference =>
1880
1881                if Is_Procedure_Attribute_Name
1882                     (Attribute_Name (The_Parent))
1883                then
1884                   return The_Parent;
1885                end if;
1886
1887             --  A raise statement can be wrapped. This will arise when the
1888             --  expression in a raise_with_expression uses the secondary
1889             --  stack, for example.
1890
1891             when N_Raise_Statement =>
1892                return The_Parent;
1893
1894             --  If the expression is within the iteration scheme of a loop,
1895             --  we must create a declaration for it, followed by an assignment
1896             --  in order to have a usable statement to wrap.
1897
1898             when N_Loop_Parameter_Specification =>
1899                return Parent (The_Parent);
1900
1901             --  The following nodes contains "dummy calls" which don't
1902             --  need to be wrapped.
1903
1904             when N_Parameter_Specification     |
1905                  N_Discriminant_Specification  |
1906                  N_Component_Declaration       =>
1907                return Empty;
1908
1909             --  The return statement is not to be wrapped when the function
1910             --  itself needs wrapping at the outer-level
1911
1912             when N_Simple_Return_Statement =>
1913                declare
1914                   Applies_To : constant Entity_Id :=
1915                                  Return_Applies_To
1916                                    (Return_Statement_Entity (The_Parent));
1917                   Return_Type : constant Entity_Id := Etype (Applies_To);
1918                begin
1919                   if Requires_Transient_Scope (Return_Type) then
1920                      return Empty;
1921                   else
1922                      return The_Parent;
1923                   end if;
1924                end;
1925
1926             --  If we leave a scope without having been able to find a node to
1927             --  wrap, something is going wrong but this can happen in error
1928             --  situation that are not detected yet (such as a dynamic string
1929             --  in a pragma export)
1930
1931             when N_Subprogram_Body     |
1932                  N_Package_Declaration |
1933                  N_Package_Body        |
1934                  N_Block_Statement     =>
1935                return Empty;
1936
1937             --  otherwise continue the search
1938
1939             when others =>
1940                null;
1941          end case;
1942       end loop;
1943    end Find_Node_To_Be_Wrapped;
1944
1945    ----------------------
1946    -- Global_Flist_Ref --
1947    ----------------------
1948
1949    function Global_Flist_Ref  (Flist_Ref : Node_Id) return Boolean is
1950       Flist : Entity_Id;
1951
1952    begin
1953       --  Look for the Global_Final_List
1954
1955       if Is_Entity_Name (Flist_Ref) then
1956          Flist := Entity (Flist_Ref);
1957
1958       --  Look for the final list associated with an access to controlled
1959
1960       elsif  Nkind (Flist_Ref) = N_Selected_Component
1961         and then Is_Entity_Name (Prefix (Flist_Ref))
1962       then
1963          Flist :=  Entity (Prefix (Flist_Ref));
1964       else
1965          return False;
1966       end if;
1967
1968       return Present (Flist)
1969         and then Present (Scope (Flist))
1970         and then Enclosing_Dynamic_Scope (Flist) = Standard_Standard;
1971    end Global_Flist_Ref;
1972
1973    ----------------------------------
1974    -- Has_New_Controlled_Component --
1975    ----------------------------------
1976
1977    function Has_New_Controlled_Component (E : Entity_Id) return Boolean is
1978       Comp : Entity_Id;
1979
1980    begin
1981       if not Is_Tagged_Type (E) then
1982          return Has_Controlled_Component (E);
1983       elsif not Is_Derived_Type (E) then
1984          return Has_Controlled_Component (E);
1985       end if;
1986
1987       Comp := First_Component (E);
1988       while Present (Comp) loop
1989
1990          if Chars (Comp) = Name_uParent then
1991             null;
1992
1993          elsif Scope (Original_Record_Component (Comp)) = E
1994            and then Needs_Finalization (Etype (Comp))
1995          then
1996             return True;
1997          end if;
1998
1999          Next_Component (Comp);
2000       end loop;
2001
2002       return False;
2003    end Has_New_Controlled_Component;
2004
2005    --------------------------
2006    -- In_Finalization_Root --
2007    --------------------------
2008
2009    --  It would seem simpler to test Scope (RTE (RE_Root_Controlled)) but
2010    --  the purpose of this function is to avoid a circular call to Rtsfind
2011    --  which would been caused by such a test.
2012
2013    function In_Finalization_Root (E : Entity_Id) return Boolean is
2014       S : constant Entity_Id := Scope (E);
2015
2016    begin
2017       return Chars (Scope (S))     = Name_System
2018         and then Chars (S)         = Name_Finalization_Root
2019         and then Scope (Scope (S)) = Standard_Standard;
2020    end  In_Finalization_Root;
2021
2022    ------------------------------------
2023    -- Insert_Actions_In_Scope_Around --
2024    ------------------------------------
2025
2026    procedure Insert_Actions_In_Scope_Around (N : Node_Id) is
2027       SE     : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
2028       Target : Node_Id;
2029
2030    begin
2031       --  If the node to be wrapped is the triggering statement of an
2032       --  asynchronous select, it is not part of a statement list. The
2033       --  actions must be inserted before the Select itself, which is
2034       --  part of some list of statements. Note that the triggering
2035       --  alternative includes the triggering statement and an optional
2036       --  statement list. If the node to be wrapped is part of that list,
2037       --  the normal insertion applies.
2038
2039       if Nkind (Parent (Node_To_Be_Wrapped)) = N_Triggering_Alternative
2040         and then not Is_List_Member (Node_To_Be_Wrapped)
2041       then
2042          Target := Parent (Parent (Node_To_Be_Wrapped));
2043       else
2044          Target := N;
2045       end if;
2046
2047       if Present (SE.Actions_To_Be_Wrapped_Before) then
2048          Insert_List_Before (Target, SE.Actions_To_Be_Wrapped_Before);
2049          SE.Actions_To_Be_Wrapped_Before := No_List;
2050       end if;
2051
2052       if Present (SE.Actions_To_Be_Wrapped_After) then
2053          Insert_List_After (Target, SE.Actions_To_Be_Wrapped_After);
2054          SE.Actions_To_Be_Wrapped_After := No_List;
2055       end if;
2056    end Insert_Actions_In_Scope_Around;
2057
2058    -----------------------
2059    -- Make_Adjust_Call --
2060    -----------------------
2061
2062    function Make_Adjust_Call
2063      (Ref         : Node_Id;
2064       Typ         : Entity_Id;
2065       Flist_Ref   : Node_Id;
2066       With_Attach : Node_Id;
2067       Allocator   : Boolean := False) return List_Id
2068    is
2069       Loc    : constant Source_Ptr := Sloc (Ref);
2070       Res    : constant List_Id    := New_List;
2071       Utyp   : Entity_Id;
2072       Proc   : Entity_Id;
2073       Cref   : Node_Id := Ref;
2074       Cref2  : Node_Id;
2075       Attach : Node_Id := With_Attach;
2076
2077    begin
2078       if Is_Class_Wide_Type (Typ) then
2079          Utyp := Underlying_Type (Base_Type (Root_Type (Typ)));
2080       else
2081          Utyp := Underlying_Type (Base_Type (Typ));
2082       end if;
2083
2084       Set_Assignment_OK (Cref);
2085
2086       --  Deal with non-tagged derivation of private views
2087
2088       if Is_Untagged_Derivation (Typ) then
2089          Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
2090          Cref := Unchecked_Convert_To (Utyp, Cref);
2091          Set_Assignment_OK (Cref);
2092          --  To prevent problems with UC see 1.156 RH ???
2093       end if;
2094
2095       --  If the underlying_type is a subtype, we are dealing with
2096       --  the completion of a private type. We need to access
2097       --  the base type and generate a conversion to it.
2098
2099       if Utyp /= Base_Type (Utyp) then
2100          pragma Assert (Is_Private_Type (Typ));
2101          Utyp := Base_Type (Utyp);
2102          Cref := Unchecked_Convert_To (Utyp, Cref);
2103       end if;
2104
2105       --  If the object is unanalyzed, set its expected type for use
2106       --  in Convert_View in case an additional conversion is needed.
2107
2108       if No (Etype (Cref))
2109         and then Nkind (Cref) /= N_Unchecked_Type_Conversion
2110       then
2111          Set_Etype (Cref, Typ);
2112       end if;
2113
2114       --  We do not need to attach to one of the Global Final Lists
2115       --  the objects whose type is Finalize_Storage_Only
2116
2117       if Finalize_Storage_Only (Typ)
2118         and then (Global_Flist_Ref (Flist_Ref)
2119           or else Entity (Constant_Value (RTE (RE_Garbage_Collected)))
2120                   = Standard_True)
2121       then
2122          Attach := Make_Integer_Literal (Loc, 0);
2123       end if;
2124
2125       --  Special case for allocators: need initialization of the chain
2126       --  pointers. For the 0 case, reset them to null.
2127
2128       if Allocator then
2129          pragma Assert (Nkind (Attach) = N_Integer_Literal);
2130
2131          if Intval (Attach) = 0 then
2132             Set_Intval (Attach, Uint_4);
2133          end if;
2134       end if;
2135
2136       --  Generate:
2137       --    Deep_Adjust (Flist_Ref, Ref, Attach);
2138
2139       if Has_Controlled_Component (Utyp)
2140         or else Is_Class_Wide_Type (Typ)
2141       then
2142          if Is_Tagged_Type (Utyp) then
2143             Proc := Find_Prim_Op (Utyp, TSS_Deep_Adjust);
2144
2145          else
2146             Proc := TSS (Utyp, TSS_Deep_Adjust);
2147          end if;
2148
2149          Cref := Convert_View (Proc, Cref, 2);
2150
2151          Append_To (Res,
2152            Make_Procedure_Call_Statement (Loc,
2153              Name => New_Reference_To (Proc, Loc),
2154              Parameter_Associations =>
2155                New_List (Flist_Ref, Cref, Attach)));
2156
2157       --  Generate:
2158       --    if With_Attach then
2159       --       Attach_To_Final_List (Ref, Flist_Ref);
2160       --    end if;
2161       --    Adjust (Ref);
2162
2163       else -- Is_Controlled (Utyp)
2164
2165          Proc  := Find_Prim_Op (Utyp, Name_Of (Adjust_Case));
2166          Cref  := Convert_View (Proc, Cref);
2167          Cref2 := New_Copy_Tree (Cref);
2168
2169          Append_To (Res,
2170            Make_Procedure_Call_Statement (Loc,
2171            Name => New_Reference_To (Proc, Loc),
2172            Parameter_Associations => New_List (Cref2)));
2173
2174          Append_To (Res, Make_Attach_Call (Cref, Flist_Ref, Attach));
2175       end if;
2176
2177       return Res;
2178    end Make_Adjust_Call;
2179
2180    ----------------------
2181    -- Make_Attach_Call --
2182    ----------------------
2183
2184    --  Generate:
2185    --    System.FI.Attach_To_Final_List (Flist, Ref, Nb_Link)
2186
2187    function Make_Attach_Call
2188      (Obj_Ref     : Node_Id;
2189       Flist_Ref   : Node_Id;
2190       With_Attach : Node_Id) return Node_Id
2191    is
2192       Loc : constant Source_Ptr := Sloc (Obj_Ref);
2193
2194    begin
2195       --  Optimization: If the number of links is statically '0', don't
2196       --  call the attach_proc.
2197
2198       if Nkind (With_Attach) = N_Integer_Literal
2199         and then Intval (With_Attach) = Uint_0
2200       then
2201          return Make_Null_Statement (Loc);
2202       end if;
2203
2204       return
2205         Make_Procedure_Call_Statement (Loc,
2206           Name => New_Reference_To (RTE (RE_Attach_To_Final_List), Loc),
2207           Parameter_Associations => New_List (
2208             Flist_Ref,
2209             OK_Convert_To (RTE (RE_Finalizable), Obj_Ref),
2210             With_Attach));
2211    end Make_Attach_Call;
2212
2213    ----------------
2214    -- Make_Clean --
2215    ----------------
2216
2217    function Make_Clean
2218      (N                          : Node_Id;
2219       Clean                      : Entity_Id;
2220       Mark                       : Entity_Id;
2221       Flist                      : Entity_Id;
2222       Is_Task                    : Boolean;
2223       Is_Master                  : Boolean;
2224       Is_Protected_Subprogram    : Boolean;
2225       Is_Task_Allocation_Block   : Boolean;
2226       Is_Asynchronous_Call_Block : Boolean;
2227       Chained_Cleanup_Action     : Node_Id) return Node_Id
2228    is
2229       Loc  : constant Source_Ptr := Sloc (Clean);
2230       Stmt : constant List_Id    := New_List;
2231
2232       Sbody        : Node_Id;
2233       Spec         : Node_Id;
2234       Name         : Node_Id;
2235       Param        : Node_Id;
2236       Param_Type   : Entity_Id;
2237       Pid          : Entity_Id := Empty;
2238       Cancel_Param : Entity_Id;
2239
2240    begin
2241       if Is_Task then
2242          if Restricted_Profile then
2243             Append_To
2244               (Stmt, Build_Runtime_Call (Loc, RE_Complete_Restricted_Task));
2245          else
2246             Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Task));
2247          end if;
2248
2249       elsif Is_Master then
2250          if Restriction_Active (No_Task_Hierarchy) = False then
2251             Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Master));
2252          end if;
2253
2254       elsif Is_Protected_Subprogram then
2255
2256          --  Add statements to the cleanup handler of the (ordinary)
2257          --  subprogram expanded to implement a protected subprogram,
2258          --  unlocking the protected object parameter and undeferring abort.
2259          --  If this is a protected procedure, and the object contains
2260          --  entries, this also calls the entry service routine.
2261
2262          --  NOTE: This cleanup handler references _object, a parameter
2263          --        to the procedure.
2264
2265          --  Find the _object parameter representing the protected object
2266
2267          Spec := Parent (Corresponding_Spec (N));
2268
2269          Param := First (Parameter_Specifications (Spec));
2270          loop
2271             Param_Type := Etype (Parameter_Type (Param));
2272
2273             if Ekind (Param_Type) = E_Record_Type then
2274                Pid := Corresponding_Concurrent_Type (Param_Type);
2275             end if;
2276
2277             exit when No (Param) or else Present (Pid);
2278             Next (Param);
2279          end loop;
2280
2281          pragma Assert (Present (Param));
2282
2283          --  If the associated protected object declares entries,
2284          --  a protected procedure has to service entry queues.
2285          --  In this case, add
2286
2287          --  Service_Entries (_object._object'Access);
2288
2289          --  _object is the record used to implement the protected object.
2290          --  It is a parameter to the protected subprogram.
2291
2292          if Nkind (Specification (N)) = N_Procedure_Specification
2293            and then Has_Entries (Pid)
2294          then
2295             case Corresponding_Runtime_Package (Pid) is
2296                when System_Tasking_Protected_Objects_Entries =>
2297                   Name := New_Reference_To (RTE (RE_Service_Entries), Loc);
2298
2299                when System_Tasking_Protected_Objects_Single_Entry =>
2300                   Name := New_Reference_To (RTE (RE_Service_Entry), Loc);
2301
2302                when others =>
2303                   raise Program_Error;
2304             end case;
2305
2306             Append_To (Stmt,
2307               Make_Procedure_Call_Statement (Loc,
2308                 Name => Name,
2309                 Parameter_Associations => New_List (
2310                   Make_Attribute_Reference (Loc,
2311                     Prefix =>
2312                       Make_Selected_Component (Loc,
2313                         Prefix => New_Reference_To (
2314                           Defining_Identifier (Param), Loc),
2315                         Selector_Name =>
2316                           Make_Identifier (Loc, Name_uObject)),
2317                     Attribute_Name => Name_Unchecked_Access))));
2318
2319          else
2320             --  Unlock (_object._object'Access);
2321
2322             --  object is the record used to implement the protected object.
2323             --  It is a parameter to the protected subprogram.
2324
2325             case Corresponding_Runtime_Package (Pid) is
2326                when System_Tasking_Protected_Objects_Entries =>
2327                   Name := New_Reference_To (RTE (RE_Unlock_Entries), Loc);
2328
2329                when System_Tasking_Protected_Objects_Single_Entry =>
2330                   Name := New_Reference_To (RTE (RE_Unlock_Entry), Loc);
2331
2332                when System_Tasking_Protected_Objects =>
2333                   Name := New_Reference_To (RTE (RE_Unlock), Loc);
2334
2335                when others =>
2336                   raise Program_Error;
2337             end case;
2338
2339             Append_To (Stmt,
2340               Make_Procedure_Call_Statement (Loc,
2341                 Name => Name,
2342                 Parameter_Associations => New_List (
2343                   Make_Attribute_Reference (Loc,
2344                     Prefix =>
2345                       Make_Selected_Component (Loc,
2346                         Prefix =>
2347                           New_Reference_To (Defining_Identifier (Param), Loc),
2348                         Selector_Name =>
2349                           Make_Identifier (Loc, Name_uObject)),
2350                     Attribute_Name => Name_Unchecked_Access))));
2351          end if;
2352
2353          if Abort_Allowed then
2354
2355             --  Abort_Undefer;
2356
2357             Append_To (Stmt,
2358               Make_Procedure_Call_Statement (Loc,
2359                 Name =>
2360                   New_Reference_To (
2361                     RTE (RE_Abort_Undefer), Loc),
2362                 Parameter_Associations => Empty_List));
2363          end if;
2364
2365       elsif Is_Task_Allocation_Block then
2366
2367          --  Add a call to Expunge_Unactivated_Tasks to the cleanup
2368          --  handler of a block created for the dynamic allocation of
2369          --  tasks:
2370
2371          --  Expunge_Unactivated_Tasks (_chain);
2372
2373          --  where _chain is the list of tasks created by the allocator
2374          --  but not yet activated. This list will be empty unless
2375          --  the block completes abnormally.
2376
2377          --  This only applies to dynamically allocated tasks;
2378          --  other unactivated tasks are completed by Complete_Task or
2379          --  Complete_Master.
2380
2381          --  NOTE: This cleanup handler references _chain, a local
2382          --        object.
2383
2384          Append_To (Stmt,
2385            Make_Procedure_Call_Statement (Loc,
2386              Name =>
2387                New_Reference_To (
2388                  RTE (RE_Expunge_Unactivated_Tasks), Loc),
2389              Parameter_Associations => New_List (
2390                New_Reference_To (Activation_Chain_Entity (N), Loc))));
2391
2392       elsif Is_Asynchronous_Call_Block then
2393
2394          --  Add a call to attempt to cancel the asynchronous entry call
2395          --  whenever the block containing the abortable part is exited.
2396
2397          --  NOTE: This cleanup handler references C, a local object
2398
2399          --  Get the argument to the Cancel procedure
2400          Cancel_Param := Entry_Cancel_Parameter (Entity (Identifier (N)));
2401
2402          --  If it is of type Communication_Block, this must be a
2403          --  protected entry call.
2404
2405          if Is_RTE (Etype (Cancel_Param), RE_Communication_Block) then
2406
2407             Append_To (Stmt,
2408
2409             --  if Enqueued (Cancel_Parameter) then
2410
2411               Make_Implicit_If_Statement (Clean,
2412                 Condition => Make_Function_Call (Loc,
2413                   Name => New_Reference_To (
2414                     RTE (RE_Enqueued), Loc),
2415                   Parameter_Associations => New_List (
2416                     New_Reference_To (Cancel_Param, Loc))),
2417                 Then_Statements => New_List (
2418
2419             --  Cancel_Protected_Entry_Call (Cancel_Param);
2420
2421                   Make_Procedure_Call_Statement (Loc,
2422                     Name => New_Reference_To (
2423                       RTE (RE_Cancel_Protected_Entry_Call), Loc),
2424                     Parameter_Associations => New_List (
2425                       New_Reference_To (Cancel_Param, Loc))))));
2426
2427          --  Asynchronous delay
2428
2429          elsif Is_RTE (Etype (Cancel_Param), RE_Delay_Block) then
2430             Append_To (Stmt,
2431               Make_Procedure_Call_Statement (Loc,
2432                 Name => New_Reference_To (RTE (RE_Cancel_Async_Delay), Loc),
2433                 Parameter_Associations => New_List (
2434                   Make_Attribute_Reference (Loc,
2435                     Prefix => New_Reference_To (Cancel_Param, Loc),
2436                     Attribute_Name => Name_Unchecked_Access))));
2437
2438          --  Task entry call
2439
2440          else
2441             --  Append call to Cancel_Task_Entry_Call (C);
2442
2443             Append_To (Stmt,
2444               Make_Procedure_Call_Statement (Loc,
2445                 Name => New_Reference_To (
2446                   RTE (RE_Cancel_Task_Entry_Call),
2447                   Loc),
2448                 Parameter_Associations => New_List (
2449                   New_Reference_To (Cancel_Param, Loc))));
2450
2451          end if;
2452       end if;
2453
2454       if Present (Flist) then
2455          Append_To (Stmt,
2456            Make_Procedure_Call_Statement (Loc,
2457              Name => New_Reference_To (RTE (RE_Finalize_List), Loc),
2458              Parameter_Associations => New_List (
2459                     New_Reference_To (Flist, Loc))));
2460       end if;
2461
2462       if Present (Mark) then
2463          Append_To (Stmt,
2464            Make_Procedure_Call_Statement (Loc,
2465              Name => New_Reference_To (RTE (RE_SS_Release), Loc),
2466              Parameter_Associations => New_List (
2467                     New_Reference_To (Mark, Loc))));
2468       end if;
2469
2470       if Present (Chained_Cleanup_Action) then
2471          Append_To (Stmt,
2472            Make_Procedure_Call_Statement (Loc,
2473              Name => Chained_Cleanup_Action));
2474       end if;
2475
2476       Sbody :=
2477         Make_Subprogram_Body (Loc,
2478           Specification =>
2479             Make_Procedure_Specification (Loc,
2480               Defining_Unit_Name => Clean),
2481
2482           Declarations  => New_List,
2483
2484           Handled_Statement_Sequence =>
2485             Make_Handled_Sequence_Of_Statements (Loc,
2486               Statements => Stmt));
2487
2488       if Present (Flist) or else Is_Task or else Is_Master then
2489          Wrap_Cleanup_Procedure (Sbody);
2490       end if;
2491
2492       --  We do not want debug information for _Clean routines,
2493       --  since it just confuses the debugging operation unless
2494       --  we are debugging generated code.
2495
2496       if not Debug_Generated_Code then
2497          Set_Debug_Info_Off (Clean, True);
2498       end if;
2499
2500       return Sbody;
2501    end Make_Clean;
2502
2503    --------------------------
2504    -- Make_Deep_Array_Body --
2505    --------------------------
2506
2507    --  Array components are initialized and adjusted in the normal order
2508    --  and finalized in the reverse order. Exceptions are handled and
2509    --  Program_Error is re-raise in the Adjust and Finalize case
2510    --  (RM 7.6.1(12)). Generate the following code :
2511    --
2512    --  procedure Deep_<P>   --  with <P> being Initialize or Adjust or Finalize
2513    --   (L : in out Finalizable_Ptr;
2514    --    V : in out Typ)
2515    --  is
2516    --  begin
2517    --     for J1 in             Typ'First (1) .. Typ'Last (1) loop
2518    --               ^ reverse ^  --  in the finalization case
2519    --        ...
2520    --           for J2 in Typ'First (n) .. Typ'Last (n) loop
2521    --                 Make_<P>_Call (Typ, V (J1, .. , Jn), L, V);
2522    --           end loop;
2523    --        ...
2524    --     end loop;
2525    --  exception                                --  not in the
2526    --     when others => raise Program_Error;   --     Initialize case
2527    --  end Deep_<P>;
2528
2529    function Make_Deep_Array_Body
2530      (Prim : Final_Primitives;
2531       Typ  : Entity_Id) return List_Id
2532    is
2533       Loc : constant Source_Ptr := Sloc (Typ);
2534
2535       Index_List : constant List_Id := New_List;
2536       --  Stores the list of references to the indexes (one per dimension)
2537
2538       function One_Component return List_Id;
2539       --  Create one statement to initialize/adjust/finalize one array
2540       --  component, designated by a full set of indexes.
2541
2542       function One_Dimension (N : Int) return List_Id;
2543       --  Create loop to deal with one dimension of the array. The single
2544       --  statement in the body of the loop initializes the inner dimensions if
2545       --  any, or else a single component.
2546
2547       -------------------
2548       -- One_Component --
2549       -------------------
2550
2551       function One_Component return List_Id is
2552          Comp_Typ : constant Entity_Id := Component_Type (Typ);
2553          Comp_Ref : constant Node_Id :=
2554                       Make_Indexed_Component (Loc,
2555                         Prefix      => Make_Identifier (Loc, Name_V),
2556                         Expressions => Index_List);
2557
2558       begin
2559          --  Set the etype of the component Reference, which is used to
2560          --  determine whether a conversion to a parent type is needed.
2561
2562          Set_Etype (Comp_Ref, Comp_Typ);
2563
2564          case Prim is
2565             when Initialize_Case =>
2566                return Make_Init_Call (Comp_Ref, Comp_Typ,
2567                         Make_Identifier (Loc, Name_L),
2568                         Make_Identifier (Loc, Name_B));
2569
2570             when Adjust_Case =>
2571                return Make_Adjust_Call (Comp_Ref, Comp_Typ,
2572                         Make_Identifier (Loc, Name_L),
2573                         Make_Identifier (Loc, Name_B));
2574
2575             when Finalize_Case =>
2576                return Make_Final_Call (Comp_Ref, Comp_Typ,
2577                         Make_Identifier (Loc, Name_B));
2578          end case;
2579       end One_Component;
2580
2581       -------------------
2582       -- One_Dimension --
2583       -------------------
2584
2585       function One_Dimension (N : Int) return List_Id is
2586          Index : Entity_Id;
2587
2588       begin
2589          if N > Number_Dimensions (Typ) then
2590             return One_Component;
2591
2592          else
2593             Index :=
2594               Make_Defining_Identifier (Loc, New_External_Name ('J', N));
2595
2596             Append_To (Index_List, New_Reference_To (Index, Loc));
2597
2598             return New_List (
2599               Make_Implicit_Loop_Statement (Typ,
2600                 Identifier => Empty,
2601                 Iteration_Scheme =>
2602                   Make_Iteration_Scheme (Loc,
2603                     Loop_Parameter_Specification =>
2604                       Make_Loop_Parameter_Specification (Loc,
2605                         Defining_Identifier => Index,
2606                         Discrete_Subtype_Definition =>
2607                           Make_Attribute_Reference (Loc,
2608                             Prefix => Make_Identifier (Loc, Name_V),
2609                             Attribute_Name  => Name_Range,
2610                             Expressions => New_List (
2611                               Make_Integer_Literal (Loc, N))),
2612                         Reverse_Present => Prim = Finalize_Case)),
2613                 Statements => One_Dimension (N + 1)));
2614          end if;
2615       end One_Dimension;
2616
2617    --  Start of processing for Make_Deep_Array_Body
2618
2619    begin
2620       return One_Dimension (1);
2621    end Make_Deep_Array_Body;
2622
2623    --------------------
2624    -- Make_Deep_Proc --
2625    --------------------
2626
2627    --  Generate:
2628    --    procedure DEEP_<prim>
2629    --      (L : IN OUT Finalizable_Ptr;    -- not for Finalize
2630    --       V : IN OUT <typ>;
2631    --       B : IN Short_Short_Integer) is
2632    --    begin
2633    --       <stmts>;
2634    --    exception                   --  Finalize and Adjust Cases only
2635    --       raise Program_Error;     --  idem
2636    --    end DEEP_<prim>;
2637
2638    function Make_Deep_Proc
2639      (Prim  : Final_Primitives;
2640       Typ   : Entity_Id;
2641       Stmts : List_Id) return Entity_Id
2642    is
2643       Loc       : constant Source_Ptr := Sloc (Typ);
2644       Formals   : List_Id;
2645       Proc_Name : Entity_Id;
2646       Handler   : List_Id := No_List;
2647       Type_B    : Entity_Id;
2648
2649    begin
2650       if Prim = Finalize_Case then
2651          Formals := New_List;
2652          Type_B := Standard_Boolean;
2653
2654       else
2655          Formals := New_List (
2656            Make_Parameter_Specification (Loc,
2657              Defining_Identifier => Make_Defining_Identifier (Loc, Name_L),
2658              In_Present          => True,
2659              Out_Present         => True,
2660              Parameter_Type      =>
2661                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
2662          Type_B := Standard_Short_Short_Integer;
2663       end if;
2664
2665       Append_To (Formals,
2666         Make_Parameter_Specification (Loc,
2667           Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
2668           In_Present          => True,
2669           Out_Present         => True,
2670           Parameter_Type      => New_Reference_To (Typ, Loc)));
2671
2672       Append_To (Formals,
2673         Make_Parameter_Specification (Loc,
2674           Defining_Identifier => Make_Defining_Identifier (Loc, Name_B),
2675           Parameter_Type      => New_Reference_To (Type_B, Loc)));
2676
2677       if Prim = Finalize_Case or else Prim = Adjust_Case then
2678          Handler := New_List (Make_Handler_For_Ctrl_Operation (Loc));
2679       end if;
2680
2681       Proc_Name :=
2682         Make_Defining_Identifier (Loc,
2683           Chars => Make_TSS_Name (Typ, Deep_Name_Of (Prim)));
2684
2685       Discard_Node (
2686         Make_Subprogram_Body (Loc,
2687           Specification =>
2688             Make_Procedure_Specification (Loc,
2689               Defining_Unit_Name       => Proc_Name,
2690               Parameter_Specifications => Formals),
2691
2692           Declarations =>  Empty_List,
2693           Handled_Statement_Sequence =>
2694             Make_Handled_Sequence_Of_Statements (Loc,
2695               Statements         => Stmts,
2696               Exception_Handlers => Handler)));
2697
2698       return Proc_Name;
2699    end Make_Deep_Proc;
2700
2701    ---------------------------
2702    -- Make_Deep_Record_Body --
2703    ---------------------------
2704
2705    --  The Deep procedures call the appropriate Controlling proc on the
2706    --  the controller component. In the init case, it also attach the
2707    --  controller to the current finalization list.
2708
2709    function Make_Deep_Record_Body
2710      (Prim : Final_Primitives;
2711       Typ  : Entity_Id) return List_Id
2712    is
2713       Loc            : constant Source_Ptr := Sloc (Typ);
2714       Controller_Typ : Entity_Id;
2715       Obj_Ref        : constant Node_Id := Make_Identifier (Loc, Name_V);
2716       Controller_Ref : constant Node_Id :=
2717                          Make_Selected_Component (Loc,
2718                            Prefix        => Obj_Ref,
2719                            Selector_Name =>
2720                              Make_Identifier (Loc, Name_uController));
2721       Res            : constant List_Id := New_List;
2722
2723    begin
2724       if Is_Immutably_Limited_Type (Typ) then
2725          Controller_Typ := RTE (RE_Limited_Record_Controller);
2726       else
2727          Controller_Typ := RTE (RE_Record_Controller);
2728       end if;
2729
2730       case Prim is
2731          when Initialize_Case =>
2732             Append_List_To (Res,
2733               Make_Init_Call (
2734                 Ref          => Controller_Ref,
2735                 Typ          => Controller_Typ,
2736                 Flist_Ref    => Make_Identifier (Loc, Name_L),
2737                 With_Attach  => Make_Identifier (Loc, Name_B)));
2738
2739             --  When the type is also a controlled type by itself,
2740             --  initialize it and attach it to the finalization chain.
2741
2742             if Is_Controlled (Typ) then
2743                Append_To (Res,
2744                  Make_Procedure_Call_Statement (Loc,
2745                    Name => New_Reference_To (
2746                      Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
2747                    Parameter_Associations =>
2748                      New_List (New_Copy_Tree (Obj_Ref))));
2749
2750                Append_To (Res, Make_Attach_Call (
2751                  Obj_Ref      => New_Copy_Tree (Obj_Ref),
2752                  Flist_Ref    => Make_Identifier (Loc, Name_L),
2753                  With_Attach => Make_Identifier (Loc, Name_B)));
2754             end if;
2755
2756          when Adjust_Case =>
2757             Append_List_To (Res,
2758               Make_Adjust_Call (Controller_Ref, Controller_Typ,
2759                 Make_Identifier (Loc, Name_L),
2760                 Make_Identifier (Loc, Name_B)));
2761
2762             --  When the type is also a controlled type by itself,
2763             --  adjust it and attach it to the finalization chain.
2764
2765             if Is_Controlled (Typ) then
2766                Append_To (Res,
2767                  Make_Procedure_Call_Statement (Loc,
2768                    Name => New_Reference_To (
2769                      Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
2770                    Parameter_Associations =>
2771                      New_List (New_Copy_Tree (Obj_Ref))));
2772
2773                Append_To (Res, Make_Attach_Call (
2774                  Obj_Ref      => New_Copy_Tree (Obj_Ref),
2775                  Flist_Ref    => Make_Identifier (Loc, Name_L),
2776                  With_Attach => Make_Identifier (Loc, Name_B)));
2777             end if;
2778
2779          when Finalize_Case =>
2780             if Is_Controlled (Typ) then
2781                Append_To (Res,
2782                  Make_Implicit_If_Statement (Obj_Ref,
2783                    Condition => Make_Identifier (Loc, Name_B),
2784                    Then_Statements => New_List (
2785                      Make_Procedure_Call_Statement (Loc,
2786                        Name => New_Reference_To (RTE (RE_Finalize_One), Loc),
2787                        Parameter_Associations => New_List (
2788                          OK_Convert_To (RTE (RE_Finalizable),
2789                            New_Copy_Tree (Obj_Ref))))),
2790
2791                    Else_Statements => New_List (
2792                      Make_Procedure_Call_Statement (Loc,
2793                        Name => New_Reference_To (
2794                          Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
2795                        Parameter_Associations =>
2796                         New_List (New_Copy_Tree (Obj_Ref))))));
2797             end if;
2798
2799             Append_List_To (Res,
2800               Make_Final_Call (Controller_Ref, Controller_Typ,
2801                 Make_Identifier (Loc, Name_B)));
2802       end case;
2803       return Res;
2804    end Make_Deep_Record_Body;
2805
2806    ----------------------
2807    -- Make_Final_Call --
2808    ----------------------
2809
2810    function Make_Final_Call
2811      (Ref         : Node_Id;
2812       Typ         : Entity_Id;
2813       With_Detach : Node_Id) return List_Id
2814    is
2815       Loc   : constant Source_Ptr := Sloc (Ref);
2816       Res   : constant List_Id    := New_List;
2817       Cref  : Node_Id;
2818       Cref2 : Node_Id;
2819       Proc  : Entity_Id;
2820       Utyp  : Entity_Id;
2821
2822    begin
2823       if Is_Class_Wide_Type (Typ) then
2824          Utyp := Root_Type (Typ);
2825          Cref := Ref;
2826
2827       elsif Is_Concurrent_Type (Typ) then
2828          Utyp := Corresponding_Record_Type (Typ);
2829          Cref := Convert_Concurrent (Ref, Typ);
2830
2831       elsif Is_Private_Type (Typ)
2832         and then Present (Full_View (Typ))
2833         and then Is_Concurrent_Type (Full_View (Typ))
2834       then
2835          Utyp := Corresponding_Record_Type (Full_View (Typ));
2836          Cref := Convert_Concurrent (Ref, Full_View (Typ));
2837       else
2838          Utyp := Typ;
2839          Cref := Ref;
2840       end if;
2841
2842       Utyp := Underlying_Type (Base_Type (Utyp));
2843       Set_Assignment_OK (Cref);
2844
2845       --  Deal with non-tagged derivation of private views. If the parent is
2846       --  now known to be protected, the finalization routine is the one
2847       --  defined on the corresponding record of the ancestor (corresponding
2848       --  records do not automatically inherit operations, but maybe they
2849       --  should???)
2850
2851       if Is_Untagged_Derivation (Typ) then
2852          if Is_Protected_Type (Typ) then
2853             Utyp := Corresponding_Record_Type (Root_Type (Base_Type (Typ)));
2854          else
2855             Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
2856          end if;
2857
2858          Cref := Unchecked_Convert_To (Utyp, Cref);
2859
2860          --  We need to set Assignment_OK to prevent problems with unchecked
2861          --  conversions, where we do not want them to be converted back in the
2862          --  case of untagged record derivation (see code in Make_*_Call
2863          --  procedures for similar situations).
2864
2865          Set_Assignment_OK (Cref);
2866       end if;
2867
2868       --  If the underlying_type is a subtype, we are dealing with
2869       --  the completion of a private type. We need to access
2870       --  the base type and generate a conversion to it.
2871
2872       if Utyp /= Base_Type (Utyp) then
2873          pragma Assert (Is_Private_Type (Typ));
2874          Utyp := Base_Type (Utyp);
2875          Cref := Unchecked_Convert_To (Utyp, Cref);
2876       end if;
2877
2878       --  Generate:
2879       --    Deep_Finalize (Ref, With_Detach);
2880
2881       if Has_Controlled_Component (Utyp)
2882         or else Is_Class_Wide_Type (Typ)
2883       then
2884          if Is_Tagged_Type (Utyp) then
2885             Proc := Find_Prim_Op (Utyp, TSS_Deep_Finalize);
2886          else
2887             Proc := TSS (Utyp, TSS_Deep_Finalize);
2888          end if;
2889
2890          Cref := Convert_View (Proc, Cref);
2891
2892          Append_To (Res,
2893            Make_Procedure_Call_Statement (Loc,
2894              Name => New_Reference_To (Proc, Loc),
2895              Parameter_Associations =>
2896                New_List (Cref, With_Detach)));
2897
2898       --  Generate:
2899       --    if With_Detach then
2900       --       Finalize_One (Ref);
2901       --    else
2902       --       Finalize (Ref);
2903       --    end if;
2904
2905       else
2906          Proc := Find_Prim_Op (Utyp, Name_Of (Finalize_Case));
2907
2908          if Chars (With_Detach) = Chars (Standard_True) then
2909             Append_To (Res,
2910               Make_Procedure_Call_Statement (Loc,
2911                 Name => New_Reference_To (RTE (RE_Finalize_One), Loc),
2912                 Parameter_Associations => New_List (
2913                   OK_Convert_To (RTE (RE_Finalizable), Cref))));
2914
2915          elsif Chars (With_Detach) = Chars (Standard_False) then
2916             Append_To (Res,
2917               Make_Procedure_Call_Statement (Loc,
2918                 Name => New_Reference_To (Proc, Loc),
2919                 Parameter_Associations =>
2920                   New_List (Convert_View (Proc, Cref))));
2921
2922          else
2923             Cref2 := New_Copy_Tree (Cref);
2924             Append_To (Res,
2925               Make_Implicit_If_Statement (Ref,
2926                 Condition => With_Detach,
2927                 Then_Statements => New_List (
2928                   Make_Procedure_Call_Statement (Loc,
2929                     Name => New_Reference_To (RTE (RE_Finalize_One), Loc),
2930                     Parameter_Associations => New_List (
2931                       OK_Convert_To (RTE (RE_Finalizable), Cref)))),
2932
2933                 Else_Statements => New_List (
2934                   Make_Procedure_Call_Statement (Loc,
2935                     Name => New_Reference_To (Proc, Loc),
2936                     Parameter_Associations =>
2937                       New_List (Convert_View (Proc, Cref2))))));
2938          end if;
2939       end if;
2940
2941       return Res;
2942    end Make_Final_Call;
2943
2944    -------------------------------------
2945    -- Make_Handler_For_Ctrl_Operation --
2946    -------------------------------------
2947
2948    --  Generate:
2949
2950    --    when E : others =>
2951    --      Raise_From_Controlled_Operation (X => E);
2952
2953    --  or:
2954
2955    --    when others =>
2956    --      raise Program_Error [finalize raised exception];
2957
2958    --  depending on whether Raise_From_Controlled_Operation is available
2959
2960    function Make_Handler_For_Ctrl_Operation
2961      (Loc : Source_Ptr) return Node_Id
2962    is
2963       E_Occ : Entity_Id;
2964       --  Choice parameter (for the first case above)
2965
2966       Raise_Node : Node_Id;
2967       --  Procedure call or raise statement
2968
2969    begin
2970       if RTE_Available (RE_Raise_From_Controlled_Operation) then
2971
2972          --  Standard runtime: add choice parameter E, and pass it to
2973          --  Raise_From_Controlled_Operation so that the original exception
2974          --  name and message can be recorded in the exception message for
2975          --  Program_Error.
2976
2977          E_Occ := Make_Defining_Identifier (Loc, Name_E);
2978          Raise_Node := Make_Procedure_Call_Statement (Loc,
2979                          Name =>
2980                            New_Occurrence_Of (
2981                              RTE (RE_Raise_From_Controlled_Operation), Loc),
2982                          Parameter_Associations => New_List (
2983                            New_Occurrence_Of (E_Occ, Loc)));
2984
2985       else
2986          --  Restricted runtime: exception messages are not supported
2987
2988          E_Occ := Empty;
2989          Raise_Node := Make_Raise_Program_Error (Loc,
2990                          Reason => PE_Finalize_Raised_Exception);
2991       end if;
2992
2993       return Make_Implicit_Exception_Handler (Loc,
2994                Exception_Choices => New_List (Make_Others_Choice (Loc)),
2995                Choice_Parameter  => E_Occ,
2996                Statements        => New_List (Raise_Node));
2997    end Make_Handler_For_Ctrl_Operation;
2998
2999    --------------------
3000    -- Make_Init_Call --
3001    --------------------
3002
3003    function Make_Init_Call
3004      (Ref          : Node_Id;
3005       Typ          : Entity_Id;
3006       Flist_Ref    : Node_Id;
3007       With_Attach  : Node_Id) return List_Id
3008    is
3009       Loc     : constant Source_Ptr := Sloc (Ref);
3010       Is_Conc : Boolean;
3011       Res     : constant List_Id := New_List;
3012       Proc    : Entity_Id;
3013       Utyp    : Entity_Id;
3014       Cref    : Node_Id;
3015       Cref2   : Node_Id;
3016       Attach  : Node_Id := With_Attach;
3017
3018    begin
3019       if Is_Concurrent_Type (Typ) then
3020          Is_Conc := True;
3021          Utyp    := Corresponding_Record_Type (Typ);
3022          Cref    := Convert_Concurrent (Ref, Typ);
3023
3024       elsif Is_Private_Type (Typ)
3025         and then Present (Full_View (Typ))
3026         and then Is_Concurrent_Type (Underlying_Type (Typ))
3027       then
3028          Is_Conc := True;
3029          Utyp    := Corresponding_Record_Type (Underlying_Type (Typ));
3030          Cref    := Convert_Concurrent (Ref, Underlying_Type (Typ));
3031
3032       else
3033          Is_Conc := False;
3034          Utyp    := Typ;
3035          Cref    := Ref;
3036       end if;
3037
3038       Utyp := Underlying_Type (Base_Type (Utyp));
3039
3040       Set_Assignment_OK (Cref);
3041
3042       --  Deal with non-tagged derivation of private views
3043
3044       if Is_Untagged_Derivation (Typ)
3045         and then not Is_Conc
3046       then
3047          Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
3048          Cref := Unchecked_Convert_To (Utyp, Cref);
3049          Set_Assignment_OK (Cref);
3050          --  To prevent problems with UC see 1.156 RH ???
3051       end if;
3052
3053       --  If the underlying_type is a subtype, we are dealing with
3054       --  the completion of a private type. We need to access
3055       --  the base type and generate a conversion to it.
3056
3057       if Utyp /= Base_Type (Utyp) then
3058          pragma Assert (Is_Private_Type (Typ));
3059          Utyp := Base_Type (Utyp);
3060          Cref := Unchecked_Convert_To (Utyp, Cref);
3061       end if;
3062
3063       --  We do not need to attach to one of the Global Final Lists
3064       --  the objects whose type is Finalize_Storage_Only
3065
3066       if Finalize_Storage_Only (Typ)
3067         and then (Global_Flist_Ref (Flist_Ref)
3068           or else Entity (Constant_Value (RTE (RE_Garbage_Collected)))
3069                   = Standard_True)
3070       then
3071          Attach := Make_Integer_Literal (Loc, 0);
3072       end if;
3073
3074       --  Generate:
3075       --    Deep_Initialize (Ref, Flist_Ref);
3076
3077       if Has_Controlled_Component (Utyp) then
3078          Proc := TSS (Utyp, Deep_Name_Of (Initialize_Case));
3079
3080          Cref := Convert_View (Proc, Cref, 2);
3081
3082          Append_To (Res,
3083            Make_Procedure_Call_Statement (Loc,
3084              Name => New_Reference_To (Proc, Loc),
3085              Parameter_Associations => New_List (
3086                Node1 => Flist_Ref,
3087                Node2 => Cref,
3088                Node3 => Attach)));
3089
3090       --  Generate:
3091       --    Attach_To_Final_List (Ref, Flist_Ref);
3092       --    Initialize (Ref);
3093
3094       else -- Is_Controlled (Utyp)
3095          Proc  := Find_Prim_Op (Utyp, Name_Of (Initialize_Case));
3096          Check_Visibly_Controlled (Initialize_Case, Typ, Proc, Cref);
3097
3098          Cref  := Convert_View (Proc, Cref);
3099          Cref2 := New_Copy_Tree (Cref);
3100
3101          Append_To (Res,
3102            Make_Procedure_Call_Statement (Loc,
3103            Name => New_Reference_To (Proc, Loc),
3104            Parameter_Associations => New_List (Cref2)));
3105
3106          Append_To (Res,
3107            Make_Attach_Call (Cref, Flist_Ref, Attach));
3108       end if;
3109
3110       return Res;
3111    end Make_Init_Call;
3112
3113    --------------------------
3114    -- Make_Transient_Block --
3115    --------------------------
3116
3117    --  If finalization is involved, this function just wraps the instruction
3118    --  into a block whose name is the transient block entity, and then
3119    --  Expand_Cleanup_Actions (called on the expansion of the handled
3120    --  sequence of statements will do the necessary expansions for
3121    --  cleanups).
3122
3123    function Make_Transient_Block
3124      (Loc    : Source_Ptr;
3125       Action : Node_Id) return Node_Id
3126    is
3127       Flist  : constant Entity_Id := Finalization_Chain_Entity (Current_Scope);
3128       Decls  : constant List_Id   := New_List;
3129       Par    : constant Node_Id   := Parent (Action);
3130       Instrs : constant List_Id   := New_List (Action);
3131       Blk    : Node_Id;
3132
3133    begin
3134       --  Case where only secondary stack use is involved
3135
3136       if VM_Target = No_VM
3137         and then Uses_Sec_Stack (Current_Scope)
3138         and then No (Flist)
3139         and then Nkind (Action) /= N_Simple_Return_Statement
3140         and then Nkind (Par) /= N_Exception_Handler
3141       then
3142          declare
3143             S  : Entity_Id;
3144             K  : Entity_Kind;
3145
3146          begin
3147             S := Scope (Current_Scope);
3148             loop
3149                K := Ekind (S);
3150
3151                --  At the outer level, no need to release the sec stack
3152
3153                if S = Standard_Standard then
3154                   Set_Uses_Sec_Stack (Current_Scope, False);
3155                   exit;
3156
3157                --  In a function, only release the sec stack if the
3158                --  function does not return on the sec stack otherwise
3159                --  the result may be lost. The caller is responsible for
3160                --  releasing.
3161
3162                elsif K = E_Function then
3163                   Set_Uses_Sec_Stack (Current_Scope, False);
3164
3165                   if not Requires_Transient_Scope (Etype (S)) then
3166                      Set_Uses_Sec_Stack (S, True);
3167                      Check_Restriction (No_Secondary_Stack, Action);
3168                   end if;
3169
3170                   exit;
3171
3172                --  In a loop or entry we should install a block encompassing
3173                --  all the construct. For now just release right away.
3174
3175                elsif K = E_Loop or else K = E_Entry then
3176                   exit;
3177
3178                --  In a procedure or a block, we release on exit of the
3179                --  procedure or block. ??? memory leak can be created by
3180                --  recursive calls.
3181
3182                elsif K = E_Procedure
3183                  or else K = E_Block
3184                then
3185                   Set_Uses_Sec_Stack (S, True);
3186                   Check_Restriction (No_Secondary_Stack, Action);
3187                   Set_Uses_Sec_Stack (Current_Scope, False);
3188                   exit;
3189
3190                else
3191                   S := Scope (S);
3192                end if;
3193             end loop;
3194          end;
3195       end if;
3196
3197       --  Insert actions stuck in the transient scopes as well as all
3198       --  freezing nodes needed by those actions
3199
3200       Insert_Actions_In_Scope_Around (Action);
3201
3202       declare
3203          Last_Inserted : Node_Id := Prev (Action);
3204       begin
3205          if Present (Last_Inserted) then
3206             Freeze_All (First_Entity (Current_Scope), Last_Inserted);
3207          end if;
3208       end;
3209
3210       Blk :=
3211         Make_Block_Statement (Loc,
3212           Identifier => New_Reference_To (Current_Scope, Loc),
3213           Declarations => Decls,
3214           Handled_Statement_Sequence =>
3215             Make_Handled_Sequence_Of_Statements (Loc, Statements => Instrs),
3216           Has_Created_Identifier => True);
3217
3218       --  When the transient scope was established, we pushed the entry for
3219       --  the transient scope onto the scope stack, so that the scope was
3220       --  active for the installation of finalizable entities etc. Now we
3221       --  must remove this entry, since we have constructed a proper block.
3222
3223       Pop_Scope;
3224
3225       return Blk;
3226    end Make_Transient_Block;
3227
3228    ------------------------
3229    -- Needs_Finalization --
3230    ------------------------
3231
3232    function Needs_Finalization (T : Entity_Id) return Boolean is
3233
3234       function Has_Some_Controlled_Component (Rec : Entity_Id) return Boolean;
3235       --  If type is not frozen yet, check explicitly among its components,
3236       --  because the Has_Controlled_Component flag is not necessarily set.
3237
3238       -----------------------------------
3239       -- Has_Some_Controlled_Component --
3240       -----------------------------------
3241
3242       function Has_Some_Controlled_Component
3243         (Rec : Entity_Id) return Boolean
3244       is
3245          Comp : Entity_Id;
3246
3247       begin
3248          if Has_Controlled_Component (Rec) then
3249             return True;
3250
3251          elsif not Is_Frozen (Rec) then
3252             if Is_Record_Type (Rec) then
3253                Comp := First_Entity (Rec);
3254
3255                while Present (Comp) loop
3256                   if not Is_Type (Comp)
3257                     and then Needs_Finalization (Etype (Comp))
3258                   then
3259                      return True;
3260                   end if;
3261
3262                   Next_Entity (Comp);
3263                end loop;
3264
3265                return False;
3266
3267             elsif Is_Array_Type (Rec) then
3268                return Needs_Finalization (Component_Type (Rec));
3269
3270             else
3271                return Has_Controlled_Component (Rec);
3272             end if;
3273          else
3274             return False;
3275          end if;
3276       end Has_Some_Controlled_Component;
3277
3278    --  Start of processing for Needs_Finalization
3279
3280    begin
3281       return
3282
3283         --  Class-wide types must be treated as controlled and therefore
3284         --  requiring finalization (because they may be extended with an
3285         --  extension that has controlled components.
3286
3287         (Is_Class_Wide_Type (T)
3288
3289           --  However, avoid treating class-wide types as controlled if
3290           --  finalization is not available and in particular CIL value
3291           --  types never have finalization).
3292
3293           and then not In_Finalization_Root (T)
3294           and then not Restriction_Active (No_Finalization)
3295           and then not Is_Value_Type (Etype (T)))
3296
3297         --  Controlled types always need finalization
3298
3299         or else Is_Controlled (T)
3300         or else Has_Some_Controlled_Component (T)
3301
3302         --  For concurrent types, test the corresponding record type
3303
3304         or else (Is_Concurrent_Type (T)
3305                   and then Present (Corresponding_Record_Type (T))
3306                   and then Needs_Finalization (Corresponding_Record_Type (T)));
3307    end Needs_Finalization;
3308
3309    ------------------------
3310    -- Node_To_Be_Wrapped --
3311    ------------------------
3312
3313    function Node_To_Be_Wrapped return Node_Id is
3314    begin
3315       return Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped;
3316    end Node_To_Be_Wrapped;
3317
3318    ----------------------------
3319    -- Set_Node_To_Be_Wrapped --
3320    ----------------------------
3321
3322    procedure Set_Node_To_Be_Wrapped (N : Node_Id) is
3323    begin
3324       Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped := N;
3325    end Set_Node_To_Be_Wrapped;
3326
3327    ----------------------------------
3328    -- Store_After_Actions_In_Scope --
3329    ----------------------------------
3330
3331    procedure Store_After_Actions_In_Scope (L : List_Id) is
3332       SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
3333
3334    begin
3335       if Present (SE.Actions_To_Be_Wrapped_After) then
3336          Insert_List_Before_And_Analyze (
3337           First (SE.Actions_To_Be_Wrapped_After), L);
3338
3339       else
3340          SE.Actions_To_Be_Wrapped_After := L;
3341
3342          if Is_List_Member (SE.Node_To_Be_Wrapped) then
3343             Set_Parent (L, Parent (SE.Node_To_Be_Wrapped));
3344          else
3345             Set_Parent (L, SE.Node_To_Be_Wrapped);
3346          end if;
3347
3348          Analyze_List (L);
3349       end if;
3350    end Store_After_Actions_In_Scope;
3351
3352    -----------------------------------
3353    -- Store_Before_Actions_In_Scope --
3354    -----------------------------------
3355
3356    procedure Store_Before_Actions_In_Scope (L : List_Id) is
3357       SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
3358
3359    begin
3360       if Present (SE.Actions_To_Be_Wrapped_Before) then
3361          Insert_List_After_And_Analyze (
3362            Last (SE.Actions_To_Be_Wrapped_Before), L);
3363
3364       else
3365          SE.Actions_To_Be_Wrapped_Before := L;
3366
3367          if Is_List_Member (SE.Node_To_Be_Wrapped) then
3368             Set_Parent (L, Parent (SE.Node_To_Be_Wrapped));
3369          else
3370             Set_Parent (L, SE.Node_To_Be_Wrapped);
3371          end if;
3372
3373          Analyze_List (L);
3374       end if;
3375    end Store_Before_Actions_In_Scope;
3376
3377    --------------------------------
3378    -- Wrap_Transient_Declaration --
3379    --------------------------------
3380
3381    --  If a transient scope has been established during the processing of the
3382    --  Expression of an Object_Declaration, it is not possible to wrap the
3383    --  declaration into a transient block as usual case, otherwise the object
3384    --  would be itself declared in the wrong scope. Therefore, all entities (if
3385    --  any) defined in the transient block are moved to the proper enclosing
3386    --  scope, furthermore, if they are controlled variables they are finalized
3387    --  right after the declaration. The finalization list of the transient
3388    --  scope is defined as a renaming of the enclosing one so during their
3389    --  initialization they will be attached to the proper finalization
3390    --  list. For instance, the following declaration :
3391
3392    --        X : Typ := F (G (A), G (B));
3393
3394    --  (where G(A) and G(B) return controlled values, expanded as _v1 and _v2)
3395    --  is expanded into :
3396
3397    --    _local_final_list_1 : Finalizable_Ptr;
3398    --    X : Typ := [ complex Expression-Action ];
3399    --    Finalize_One(_v1);
3400    --    Finalize_One (_v2);
3401
3402    procedure Wrap_Transient_Declaration (N : Node_Id) is
3403       S              : Entity_Id;
3404       LC             : Entity_Id := Empty;
3405       Nodes          : List_Id;
3406       Loc            : constant Source_Ptr := Sloc (N);
3407       First_Decl_Loc : Source_Ptr;
3408       Enclosing_S    : Entity_Id;
3409       Uses_SS        : Boolean;
3410       Next_N         : constant Node_Id := Next (N);
3411
3412    begin
3413       S := Current_Scope;
3414       Enclosing_S := Scope (S);
3415
3416       --  Insert Actions kept in the Scope stack
3417
3418       Insert_Actions_In_Scope_Around (N);
3419
3420       --  If the declaration is consuming some secondary stack, mark the
3421       --  Enclosing scope appropriately.
3422
3423       Uses_SS := Uses_Sec_Stack (S);
3424       Pop_Scope;
3425
3426       --  Create a List controller and rename the final list to be its
3427       --  internal final pointer:
3428       --       Lxxx : Simple_List_Controller;
3429       --       Fxxx : Finalizable_Ptr renames Lxxx.F;
3430
3431       if Present (Finalization_Chain_Entity (S)) then
3432          LC := Make_Temporary (Loc, 'L');
3433
3434          --  Use the Sloc of the first declaration of N's containing list, to
3435          --  maintain monotonicity of source-line stepping during debugging.
3436
3437          First_Decl_Loc := Sloc (First (List_Containing (N)));
3438
3439          Nodes := New_List (
3440            Make_Object_Declaration (First_Decl_Loc,
3441              Defining_Identifier => LC,
3442              Object_Definition   =>
3443                New_Reference_To
3444                  (RTE (RE_Simple_List_Controller), First_Decl_Loc)),
3445
3446            Make_Object_Renaming_Declaration (First_Decl_Loc,
3447              Defining_Identifier => Finalization_Chain_Entity (S),
3448              Subtype_Mark =>
3449                New_Reference_To (RTE (RE_Finalizable_Ptr), First_Decl_Loc),
3450              Name =>
3451                Make_Selected_Component (Loc,
3452                  Prefix        => New_Reference_To (LC, First_Decl_Loc),
3453                  Selector_Name => Make_Identifier (First_Decl_Loc, Name_F))));
3454
3455          --  Put the declaration at the beginning of the declaration part
3456          --  to make sure it will be before all other actions that have been
3457          --  inserted before N.
3458
3459          Insert_List_Before_And_Analyze (First (List_Containing (N)), Nodes);
3460
3461          --  Generate the Finalization calls by finalizing the list controller
3462          --  right away. It will be re-finalized on scope exit but it doesn't
3463          --  matter. It cannot be done when the call initializes a renaming
3464          --  object though because in this case, the object becomes a pointer
3465          --  to the temporary and thus increases its life span. Ditto if this
3466          --  is a renaming of a component of an expression (such as a function
3467          --  call).
3468
3469          --  Note that there is a problem if an actual in the call needs
3470          --  finalization, because in that case the call itself is the master,
3471          --  and the actual should be finalized on return from the call ???
3472
3473          if Nkind (N) = N_Object_Renaming_Declaration
3474            and then Needs_Finalization (Etype (Defining_Identifier (N)))
3475          then
3476             null;
3477
3478          elsif Nkind (N) = N_Object_Renaming_Declaration
3479            and then
3480              Nkind_In (Renamed_Object (Defining_Identifier (N)),
3481                        N_Selected_Component,
3482                        N_Indexed_Component)
3483            and then
3484              Needs_Finalization
3485                (Etype (Prefix (Renamed_Object (Defining_Identifier (N)))))
3486          then
3487             null;
3488
3489          else
3490             Nodes :=
3491               Make_Final_Call
3492                 (Ref         => New_Reference_To (LC, Loc),
3493                  Typ         => Etype (LC),
3494                  With_Detach => New_Reference_To (Standard_False, Loc));
3495
3496             if Present (Next_N) then
3497                Insert_List_Before_And_Analyze (Next_N, Nodes);
3498             else
3499                Append_List_To (List_Containing (N), Nodes);
3500             end if;
3501          end if;
3502       end if;
3503
3504       --  Put the local entities back in the enclosing scope, and set the
3505       --  Is_Public flag appropriately.
3506
3507       Transfer_Entities (S, Enclosing_S);
3508
3509       --  Mark the enclosing dynamic scope so that the sec stack will be
3510       --  released upon its exit unless this is a function that returns on
3511       --  the sec stack in which case this will be done by the caller.
3512
3513       if VM_Target = No_VM and then Uses_SS then
3514          S := Enclosing_Dynamic_Scope (S);
3515
3516          if Ekind (S) = E_Function
3517            and then Requires_Transient_Scope (Etype (S))
3518          then
3519             null;
3520          else
3521             Set_Uses_Sec_Stack (S);
3522             Check_Restriction (No_Secondary_Stack, N);
3523          end if;
3524       end if;
3525    end Wrap_Transient_Declaration;
3526
3527    -------------------------------
3528    -- Wrap_Transient_Expression --
3529    -------------------------------
3530
3531    --  Insert actions before <Expression>:
3532
3533    --  (lines marked with <CTRL> are expanded only in presence of Controlled
3534    --   objects needing finalization)
3535
3536    --     _E : Etyp;
3537    --     declare
3538    --        _M : constant Mark_Id := SS_Mark;
3539    --        Local_Final_List : System.FI.Finalizable_Ptr;    <CTRL>
3540
3541    --        procedure _Clean is
3542    --        begin
3543    --           Abort_Defer;
3544    --           System.FI.Finalize_List (Local_Final_List);   <CTRL>
3545    --           SS_Release (M);
3546    --           Abort_Undefer;
3547    --        end _Clean;
3548
3549    --     begin
3550    --        _E := <Expression>;
3551    --     at end
3552    --        _Clean;
3553    --     end;
3554
3555    --    then expression is replaced by _E
3556
3557    procedure Wrap_Transient_Expression (N : Node_Id) is
3558       Loc  : constant Source_Ptr := Sloc (N);
3559       E    : constant Entity_Id  := Make_Temporary (Loc, 'E', N);
3560       Etyp : constant Entity_Id  := Etype (N);
3561       Expr : constant Node_Id    := Relocate_Node (N);
3562
3563    begin
3564       Insert_Actions (N, New_List (
3565         Make_Object_Declaration (Loc,
3566           Defining_Identifier => E,
3567           Object_Definition   => New_Reference_To (Etyp, Loc)),
3568
3569         Make_Transient_Block (Loc,
3570           Action =>
3571             Make_Assignment_Statement (Loc,
3572               Name       => New_Reference_To (E, Loc),
3573               Expression => Expr))));
3574
3575       Rewrite (N, New_Reference_To (E, Loc));
3576       Analyze_And_Resolve (N, Etyp);
3577    end Wrap_Transient_Expression;
3578
3579    ------------------------------
3580    -- Wrap_Transient_Statement --
3581    ------------------------------
3582
3583    --  Transform <Instruction> into
3584
3585    --  (lines marked with <CTRL> are expanded only in presence of Controlled
3586    --   objects needing finalization)
3587
3588    --    declare
3589    --       _M : Mark_Id := SS_Mark;
3590    --       Local_Final_List : System.FI.Finalizable_Ptr ;    <CTRL>
3591
3592    --       procedure _Clean is
3593    --       begin
3594    --          Abort_Defer;
3595    --          System.FI.Finalize_List (Local_Final_List);    <CTRL>
3596    --          SS_Release (_M);
3597    --          Abort_Undefer;
3598    --       end _Clean;
3599
3600    --    begin
3601    --       <Instruction>;
3602    --    at end
3603    --       _Clean;
3604    --    end;
3605
3606    procedure Wrap_Transient_Statement (N : Node_Id) is
3607       Loc           : constant Source_Ptr := Sloc (N);
3608       New_Statement : constant Node_Id := Relocate_Node (N);
3609
3610    begin
3611       Rewrite (N, Make_Transient_Block (Loc, New_Statement));
3612
3613       --  With the scope stack back to normal, we can call analyze on the
3614       --  resulting block. At this point, the transient scope is being
3615       --  treated like a perfectly normal scope, so there is nothing
3616       --  special about it.
3617
3618       --  Note: Wrap_Transient_Statement is called with the node already
3619       --  analyzed (i.e. Analyzed (N) is True). This is important, since
3620       --  otherwise we would get a recursive processing of the node when
3621       --  we do this Analyze call.
3622
3623       Analyze (N);
3624    end Wrap_Transient_Statement;
3625
3626 end Exp_Ch7;