OSDN Git Service

2009-04-10 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch9.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 9                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2008, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Einfo;    use Einfo;
29 with Elists;   use Elists;
30 with Errout;   use Errout;
31 with Exp_Ch3;  use Exp_Ch3;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Ch6;  use Exp_Ch6;
34 with Exp_Dbug; use Exp_Dbug;
35 with Exp_Disp; use Exp_Disp;
36 with Exp_Sel;  use Exp_Sel;
37 with Exp_Smem; use Exp_Smem;
38 with Exp_Tss;  use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Freeze;   use Freeze;
41 with Hostparm;
42 with Itypes;   use Itypes;
43 with Namet;    use Namet;
44 with Nlists;   use Nlists;
45 with Nmake;    use Nmake;
46 with Opt;      use Opt;
47 with Restrict; use Restrict;
48 with Rident;   use Rident;
49 with Rtsfind;  use Rtsfind;
50 with Sem;      use Sem;
51 with Sem_Aux;  use Sem_Aux;
52 with Sem_Ch6;  use Sem_Ch6;
53 with Sem_Ch8;  use Sem_Ch8;
54 with Sem_Ch11; use Sem_Ch11;
55 with Sem_Elab; use Sem_Elab;
56 with Sem_Res;  use Sem_Res;
57 with Sem_Util; use Sem_Util;
58 with Sinfo;    use Sinfo;
59 with Snames;   use Snames;
60 with Stand;    use Stand;
61 with Stringt;  use Stringt;
62 with Targparm; use Targparm;
63 with Tbuild;   use Tbuild;
64 with Uintp;    use Uintp;
65
66 package body Exp_Ch9 is
67
68    --  The following constant establishes the upper bound for the index of
69    --  an entry family. It is used to limit the allocated size of protected
70    --  types with defaulted discriminant of an integer type, when the bound
71    --  of some entry family depends on a discriminant. The limitation to
72    --  entry families of 128K should be reasonable in all cases, and is a
73    --  documented implementation restriction. It will be lifted when protected
74    --  entry families are re-implemented as a single ordered queue.
75
76    Entry_Family_Bound : constant Int := 2**16;
77
78    -----------------------
79    -- Local Subprograms --
80    -----------------------
81
82    function Actual_Index_Expression
83      (Sloc  : Source_Ptr;
84       Ent   : Entity_Id;
85       Index : Node_Id;
86       Tsk   : Entity_Id) return Node_Id;
87    --  Compute the index position for an entry call. Tsk is the target task. If
88    --  the bounds of some entry family depend on discriminants, the expression
89    --  computed by this function uses the discriminants of the target task.
90
91    procedure Add_Object_Pointer
92      (Loc      : Source_Ptr;
93       Conc_Typ : Entity_Id;
94       Decls    : List_Id);
95    --  Prepend an object pointer declaration to the declaration list Decls.
96    --  This object pointer is initialized to a type conversion of the System.
97    --  Address pointer passed to entry barrier functions and entry body
98    --  procedures.
99
100    procedure Add_Formal_Renamings
101      (Spec  : Node_Id;
102       Decls : List_Id;
103       Ent   : Entity_Id;
104       Loc   : Source_Ptr);
105    --  Create renaming declarations for the formals, inside the procedure that
106    --  implements an entry body. The renamings make the original names of the
107    --  formals accessible to gdb, and serve no other purpose.
108    --    Spec is the specification of the procedure being built.
109    --    Decls is the list of declarations to be enhanced.
110    --    Ent is the entity for the original entry body.
111
112    function Build_Accept_Body (Astat : Node_Id) return Node_Id;
113    --  Transform accept statement into a block with added exception handler.
114    --  Used both for simple accept statements and for accept alternatives in
115    --  select statements. Astat is the accept statement.
116
117    function Build_Barrier_Function
118      (N   : Node_Id;
119       Ent : Entity_Id;
120       Pid : Node_Id) return Node_Id;
121    --  Build the function body returning the value of the barrier expression
122    --  for the specified entry body.
123
124    function Build_Barrier_Function_Specification
125      (Loc    : Source_Ptr;
126       Def_Id : Entity_Id) return Node_Id;
127    --  Build a specification for a function implementing the protected entry
128    --  barrier of the specified entry body.
129
130    function Build_Entry_Count_Expression
131      (Concurrent_Type : Node_Id;
132       Component_List  : List_Id;
133       Loc             : Source_Ptr) return Node_Id;
134    --  Compute number of entries for concurrent object. This is a count of
135    --  simple entries, followed by an expression that computes the length
136    --  of the range of each entry family. A single array with that size is
137    --  allocated for each concurrent object of the type.
138
139    function Build_Parameter_Block
140      (Loc     : Source_Ptr;
141       Actuals : List_Id;
142       Formals : List_Id;
143       Decls   : List_Id) return Entity_Id;
144    --  Generate an access type for each actual parameter in the list Actuals.
145    --  Create an encapsulating record that contains all the actuals and return
146    --  its type. Generate:
147    --    type Ann1 is access all <actual1-type>
148    --    ...
149    --    type AnnN is access all <actualN-type>
150    --    type Pnn is record
151    --       <formal1> : Ann1;
152    --       ...
153    --       <formalN> : AnnN;
154    --    end record;
155
156    procedure Build_Wrapper_Bodies
157      (Loc : Source_Ptr;
158       Typ : Entity_Id;
159       N   : Node_Id);
160    --  Ada 2005 (AI-345): Typ is either a concurrent type or the corresponding
161    --  record of a concurrent type. N is the insertion node where all bodies
162    --  will be placed. This routine builds the bodies of the subprograms which
163    --  serve as an indirection mechanism to overriding primitives of concurrent
164    --  types, entries and protected procedures. Any new body is analyzed.
165
166    procedure Build_Wrapper_Specs
167      (Loc : Source_Ptr;
168       Typ : Entity_Id;
169       N   : in out Node_Id);
170    --  Ada 2005 (AI-345): Typ is either a concurrent type or the corresponding
171    --  record of a concurrent type. N is the insertion node where all specs
172    --  will be placed. This routine builds the specs of the subprograms which
173    --  serve as an indirection mechanism to overriding primitives of concurrent
174    --  types, entries and protected procedures. Any new spec is analyzed.
175
176    function Build_Find_Body_Index (Typ : Entity_Id) return Node_Id;
177    --  Build the function that translates the entry index in the call
178    --  (which depends on the size of entry families) into an index into the
179    --  Entry_Bodies_Array, to determine the body and barrier function used
180    --  in a protected entry call. A pointer to this function appears in every
181    --  protected object.
182
183    function Build_Find_Body_Index_Spec (Typ : Entity_Id) return Node_Id;
184    --  Build subprogram declaration for previous one
185
186    function Build_Protected_Entry
187      (N   : Node_Id;
188       Ent : Entity_Id;
189       Pid : Node_Id) return Node_Id;
190    --  Build the procedure implementing the statement sequence of the specified
191    --  entry body.
192
193    function Build_Protected_Entry_Specification
194      (Loc    : Source_Ptr;
195       Def_Id : Entity_Id;
196       Ent_Id : Entity_Id) return Node_Id;
197    --  Build a specification for the procedure implementing the statements of
198    --  the specified entry body. Add attributes associating it with the entry
199    --  defining identifier Ent_Id.
200
201    function Build_Protected_Spec
202      (N           : Node_Id;
203       Obj_Type    : Entity_Id;
204       Ident       : Entity_Id;
205       Unprotected : Boolean := False) return List_Id;
206    --  Utility shared by Build_Protected_Sub_Spec and Expand_Access_Protected_
207    --  Subprogram_Type. Builds signature of protected subprogram, adding the
208    --  formal that corresponds to the object itself. For an access to protected
209    --  subprogram, there is no object type to specify, so the parameter has
210    --  type Address and mode In. An indirect call through such a pointer will
211    --  convert the address to a reference to the actual object. The object is
212    --  a limited record and therefore a by_reference type.
213
214    function Build_Protected_Subprogram_Body
215      (N         : Node_Id;
216       Pid       : Node_Id;
217       N_Op_Spec : Node_Id) return Node_Id;
218    --  This function is used to construct the protected version of a protected
219    --  subprogram. Its statement sequence first defers abort, then locks
220    --  the associated protected object, and then enters a block that contains
221    --  a call to the unprotected version of the subprogram (for details, see
222    --  Build_Unprotected_Subprogram_Body). This block statement requires
223    --  a cleanup handler that unlocks the object in all cases.
224    --  (see Exp_Ch7.Expand_Cleanup_Actions).
225
226    function Build_Selected_Name
227      (Prefix      : Entity_Id;
228       Selector    : Entity_Id;
229       Append_Char : Character := ' ') return Name_Id;
230    --  Build a name in the form of Prefix__Selector, with an optional
231    --  character appended. This is used for internal subprograms generated
232    --  for operations of protected types, including barrier functions.
233    --  For the subprograms generated for entry bodies and entry barriers,
234    --  the generated name includes a sequence number that makes names
235    --  unique in the presence of entry overloading. This is necessary
236    --  because entry body procedures and barrier functions all have the
237    --  same signature.
238
239    procedure Build_Simple_Entry_Call
240      (N       : Node_Id;
241       Concval : Node_Id;
242       Ename   : Node_Id;
243       Index   : Node_Id);
244    --  Some comments here would be useful ???
245
246    function Build_Task_Proc_Specification (T : Entity_Id) return Node_Id;
247    --  This routine constructs a specification for the procedure that we will
248    --  build for the task body for task type T. The spec has the form:
249    --
250    --    procedure tnameB (_Task : access tnameV);
251    --
252    --  where name is the character name taken from the task type entity that
253    --  is passed as the argument to the procedure, and tnameV is the task
254    --  value type that is associated with the task type.
255
256    function Build_Unprotected_Subprogram_Body
257      (N   : Node_Id;
258       Pid : Node_Id) return Node_Id;
259    --  This routine constructs the unprotected version of a protected
260    --  subprogram body, which is contains all of the code in the
261    --  original, unexpanded body. This is the version of the protected
262    --  subprogram that is called from all protected operations on the same
263    --  object, including the protected version of the same subprogram.
264
265    procedure Collect_Entry_Families
266      (Loc          : Source_Ptr;
267       Cdecls       : List_Id;
268       Current_Node : in out Node_Id;
269       Conctyp      : Entity_Id);
270    --  For each entry family in a concurrent type, create an anonymous array
271    --  type of the right size, and add a component to the corresponding_record.
272
273    function Concurrent_Object
274      (Spec_Id  : Entity_Id;
275       Conc_Typ : Entity_Id) return Entity_Id;
276    --  Given a subprogram entity Spec_Id and concurrent type Conc_Typ, return
277    --  the entity associated with the concurrent object in the Protected_Body_
278    --  Subprogram or the Task_Body_Procedure of Spec_Id. The returned entity
279    --  denotes formal parameter _O, _object or _task.
280
281    function Copy_Result_Type (Res : Node_Id) return Node_Id;
282    --  Copy the result type of a function specification, when building the
283    --  internal operation corresponding to a protected function, or when
284    --  expanding an access to protected function. If the result is an anonymous
285    --  access to subprogram itself, we need to create a new signature with the
286    --  same parameter names and the same resolved types, but with new entities
287    --  for the formals.
288
289    procedure Debug_Private_Data_Declarations (Decls : List_Id);
290    --  Decls is a list which may contain the declarations created by Install_
291    --  Private_Data_Declarations. All generated entities are marked as needing
292    --  debug info and debug nodes are manually generation where necessary. This
293    --  step of the expansion must to be done after private data has been moved
294    --  to its final resting scope to ensure proper visibility of debug objects.
295
296    function Family_Offset
297      (Loc  : Source_Ptr;
298       Hi   : Node_Id;
299       Lo   : Node_Id;
300       Ttyp : Entity_Id;
301       Cap  : Boolean) return Node_Id;
302    --  Compute (Hi - Lo) for two entry family indices. Hi is the index in
303    --  an accept statement, or the upper bound in the discrete subtype of
304    --  an entry declaration. Lo is the corresponding lower bound. Ttyp is
305    --  the concurrent type of the entry. If Cap is true, the result is
306    --  capped according to Entry_Family_Bound.
307
308    function Family_Size
309      (Loc  : Source_Ptr;
310       Hi   : Node_Id;
311       Lo   : Node_Id;
312       Ttyp : Entity_Id;
313       Cap  : Boolean) return Node_Id;
314    --  Compute (Hi - Lo) + 1 Max 0, to determine the number of entries in
315    --  a family, and handle properly the superflat case. This is equivalent
316    --  to the use of 'Length on the index type, but must use Family_Offset
317    --  to handle properly the case of bounds that depend on discriminants.
318    --  If Cap is true, the result is capped according to Entry_Family_Bound.
319
320    procedure Extract_Dispatching_Call
321      (N        : Node_Id;
322       Call_Ent : out Entity_Id;
323       Object   : out Entity_Id;
324       Actuals  : out List_Id;
325       Formals  : out List_Id);
326    --  Given a dispatching call, extract the entity of the name of the call,
327    --  its object parameter, its actual parameters and the formal parameters
328    --  of the overridden interface-level version.
329
330    procedure Extract_Entry
331      (N       : Node_Id;
332       Concval : out Node_Id;
333       Ename   : out Node_Id;
334       Index   : out Node_Id);
335    --  Given an entry call, returns the associated concurrent object,
336    --  the entry name, and the entry family index.
337
338    function Find_Task_Or_Protected_Pragma
339      (T : Node_Id;
340       P : Name_Id) return Node_Id;
341    --  Searches the task or protected definition T for the first occurrence
342    --  of the pragma whose name is given by P. The caller has ensured that
343    --  the pragma is present in the task definition. A special case is that
344    --  when P is Name_uPriority, the call will also find Interrupt_Priority.
345    --  ??? Should be implemented with the rep item chain mechanism.
346
347    function Index_Object (Spec_Id : Entity_Id) return Entity_Id;
348    --  Given a subprogram identifier, return the entity which is associated
349    --  with the protection entry index in the Protected_Body_Subprogram or the
350    --  Task_Body_Procedure of Spec_Id. The returned entity denotes formal
351    --  parameter _E.
352
353    function Is_Potentially_Large_Family
354      (Base_Index : Entity_Id;
355       Conctyp    : Entity_Id;
356       Lo         : Node_Id;
357       Hi         : Node_Id) return Boolean;
358
359    function Is_Private_Primitive_Subprogram (Id : Entity_Id) return Boolean;
360    --  Determine whether Id is a function or a procedure and is marked as a
361    --  private primitive.
362
363    function Null_Statements (Stats : List_Id) return Boolean;
364    --  Used to check DO-END sequence. Checks for equivalent of DO NULL; END.
365    --  Allows labels, and pragma Warnings/Unreferenced in the sequence as
366    --  well to still count as null. Returns True for a null sequence. The
367    --  argument is the list of statements from the DO-END sequence.
368
369    function Parameter_Block_Pack
370      (Loc     : Source_Ptr;
371       Blk_Typ : Entity_Id;
372       Actuals : List_Id;
373       Formals : List_Id;
374       Decls   : List_Id;
375       Stmts   : List_Id) return Entity_Id;
376    --  Set the components of the generated parameter block with the values of
377    --  the actual parameters. Generate aliased temporaries to capture the
378    --  values for types that are passed by copy. Otherwise generate a reference
379    --  to the actual's value. Return the address of the aggregate block.
380    --  Generate:
381    --    Jnn1 : alias <formal-type1>;
382    --    Jnn1 := <actual1>;
383    --    ...
384    --    P : Blk_Typ := (
385    --      Jnn1'unchecked_access;
386    --      <actual2>'reference;
387    --      ...);
388
389    function Parameter_Block_Unpack
390      (Loc     : Source_Ptr;
391       P       : Entity_Id;
392       Actuals : List_Id;
393       Formals : List_Id) return List_Id;
394    --  Retrieve the values of the components from the parameter block and
395    --  assign then to the original actual parameters. Generate:
396    --    <actual1> := P.<formal1>;
397    --    ...
398    --    <actualN> := P.<formalN>;
399
400    function Trivial_Accept_OK return Boolean;
401    --  If there is no DO-END block for an accept, or if the DO-END block has
402    --  only null statements, then it is possible to do the Rendezvous with much
403    --  less overhead using the Accept_Trivial routine in the run-time library.
404    --  However, this is not always a valid optimization. Whether it is valid or
405    --  not depends on the Task_Dispatching_Policy. The issue is whether a full
406    --  rescheduling action is required or not. In FIFO_Within_Priorities, such
407    --  a rescheduling is required, so this optimization is not allowed. This
408    --  function returns True if the optimization is permitted.
409
410    -----------------------------
411    -- Actual_Index_Expression --
412    -----------------------------
413
414    function Actual_Index_Expression
415      (Sloc  : Source_Ptr;
416       Ent   : Entity_Id;
417       Index : Node_Id;
418       Tsk   : Entity_Id) return Node_Id
419    is
420       Ttyp : constant Entity_Id := Etype (Tsk);
421       Expr : Node_Id;
422       Num  : Node_Id;
423       Lo   : Node_Id;
424       Hi   : Node_Id;
425       Prev : Entity_Id;
426       S    : Node_Id;
427
428       function Actual_Family_Offset (Hi, Lo : Node_Id) return Node_Id;
429       --  Compute difference between bounds of entry family
430
431       --------------------------
432       -- Actual_Family_Offset --
433       --------------------------
434
435       function Actual_Family_Offset (Hi, Lo : Node_Id) return Node_Id is
436
437          function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id;
438          --  Replace a reference to a discriminant with a selected component
439          --  denoting the discriminant of the target task.
440
441          -----------------------------
442          -- Actual_Discriminant_Ref --
443          -----------------------------
444
445          function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id is
446             Typ : constant Entity_Id := Etype (Bound);
447             B   : Node_Id;
448
449          begin
450             if not Is_Entity_Name (Bound)
451               or else Ekind (Entity (Bound)) /= E_Discriminant
452             then
453                if Nkind (Bound) = N_Attribute_Reference then
454                   return Bound;
455                else
456                   B := New_Copy_Tree (Bound);
457                end if;
458
459             else
460                B :=
461                  Make_Selected_Component (Sloc,
462                    Prefix => New_Copy_Tree (Tsk),
463                    Selector_Name => New_Occurrence_Of (Entity (Bound), Sloc));
464
465                Analyze_And_Resolve (B, Typ);
466             end if;
467
468             return
469               Make_Attribute_Reference (Sloc,
470                 Attribute_Name => Name_Pos,
471                 Prefix => New_Occurrence_Of (Etype (Bound), Sloc),
472                 Expressions => New_List (B));
473          end Actual_Discriminant_Ref;
474
475       --  Start of processing for Actual_Family_Offset
476
477       begin
478          return
479            Make_Op_Subtract (Sloc,
480              Left_Opnd  => Actual_Discriminant_Ref (Hi),
481              Right_Opnd => Actual_Discriminant_Ref (Lo));
482       end Actual_Family_Offset;
483
484    --  Start of processing for Actual_Index_Expression
485
486    begin
487       --  The queues of entries and entry families appear in textual order in
488       --  the associated record. The entry index is computed as the sum of the
489       --  number of queues for all entries that precede the designated one, to
490       --  which is added the index expression, if this expression denotes a
491       --  member of a family.
492
493       --  The following is a place holder for the count of simple entries
494
495       Num := Make_Integer_Literal (Sloc, 1);
496
497       --  We construct an expression which is a series of addition operations.
498       --  See comments in Entry_Index_Expression, which is identical in
499       --  structure.
500
501       if Present (Index) then
502          S := Etype (Discrete_Subtype_Definition (Declaration_Node (Ent)));
503
504          Expr :=
505            Make_Op_Add (Sloc,
506              Left_Opnd  => Num,
507
508              Right_Opnd =>
509                Actual_Family_Offset (
510                  Make_Attribute_Reference (Sloc,
511                    Attribute_Name => Name_Pos,
512                    Prefix => New_Reference_To (Base_Type (S), Sloc),
513                    Expressions => New_List (Relocate_Node (Index))),
514                  Type_Low_Bound (S)));
515       else
516          Expr := Num;
517       end if;
518
519       --  Now add lengths of preceding entries and entry families
520
521       Prev := First_Entity (Ttyp);
522
523       while Chars (Prev) /= Chars (Ent)
524         or else (Ekind (Prev) /= Ekind (Ent))
525         or else not Sem_Ch6.Type_Conformant (Ent, Prev)
526       loop
527          if Ekind (Prev) = E_Entry then
528             Set_Intval (Num, Intval (Num) + 1);
529
530          elsif Ekind (Prev) = E_Entry_Family then
531             S :=
532               Etype (Discrete_Subtype_Definition (Declaration_Node (Prev)));
533
534             --  The need for the following full view retrieval stems from
535             --  this complex case of nested generics and tasking:
536
537             --     generic
538             --        type Formal_Index is range <>;
539             --        ...
540             --     package Outer is
541             --        type Index is private;
542             --        generic
543             --           ...
544             --        package Inner is
545             --           procedure P;
546             --        end Inner;
547             --     private
548             --        type Index is new Formal_Index range 1 .. 10;
549             --     end Outer;
550
551             --     package body Outer is
552             --        task type T is
553             --           entry Fam (Index);  --  (2)
554             --           entry E;
555             --        end T;
556             --        package body Inner is  --  (3)
557             --           procedure P is
558             --           begin
559             --              T.E;             --  (1)
560             --           end P;
561             --       end Inner;
562             --       ...
563
564             --  We are currently building the index expression for the entry
565             --  call "T.E" (1). Part of the expansion must mention the range
566             --  of the discrete type "Index" (2) of entry family "Fam".
567             --  However only the private view of type "Index" is available to
568             --  the inner generic (3) because there was no prior mention of
569             --  the type inside "Inner". This visibility requirement is
570             --  implicit and cannot be detected during the construction of
571             --  the generic trees and needs special handling.
572
573             if In_Instance_Body
574               and then Is_Private_Type (S)
575               and then Present (Full_View (S))
576             then
577                S := Full_View (S);
578             end if;
579
580             Lo := Type_Low_Bound  (S);
581             Hi := Type_High_Bound (S);
582
583             Expr :=
584               Make_Op_Add (Sloc,
585               Left_Opnd  => Expr,
586               Right_Opnd =>
587                 Make_Op_Add (Sloc,
588                   Left_Opnd =>
589                     Actual_Family_Offset (Hi, Lo),
590                   Right_Opnd =>
591                     Make_Integer_Literal (Sloc, 1)));
592
593          --  Other components are anonymous types to be ignored
594
595          else
596             null;
597          end if;
598
599          Next_Entity (Prev);
600       end loop;
601
602       return Expr;
603    end Actual_Index_Expression;
604
605    --------------------------
606    -- Add_Formal_Renamings --
607    --------------------------
608
609    procedure Add_Formal_Renamings
610      (Spec  : Node_Id;
611       Decls : List_Id;
612       Ent   : Entity_Id;
613       Loc   : Source_Ptr)
614    is
615       Ptr : constant Entity_Id :=
616               Defining_Identifier
617                 (Next (First (Parameter_Specifications (Spec))));
618       --  The name of the formal that holds the address of the parameter block
619       --  for the call.
620
621       Comp   : Entity_Id;
622       Decl   : Node_Id;
623       Formal : Entity_Id;
624       New_F  : Entity_Id;
625
626    begin
627       Formal := First_Formal (Ent);
628       while Present (Formal) loop
629          Comp := Entry_Component (Formal);
630          New_F :=
631            Make_Defining_Identifier (Sloc (Formal),
632              Chars => Chars (Formal));
633          Set_Etype (New_F, Etype (Formal));
634          Set_Scope (New_F, Ent);
635
636          --  Now we set debug info needed on New_F even though it does not
637          --  come from source, so that the debugger will get the right
638          --  information for these generated names.
639
640          Set_Debug_Info_Needed (New_F);
641
642          if Ekind (Formal) = E_In_Parameter then
643             Set_Ekind (New_F, E_Constant);
644          else
645             Set_Ekind (New_F, E_Variable);
646             Set_Extra_Constrained (New_F, Extra_Constrained (Formal));
647          end if;
648
649          Set_Actual_Subtype (New_F, Actual_Subtype (Formal));
650
651          Decl :=
652            Make_Object_Renaming_Declaration (Loc,
653            Defining_Identifier => New_F,
654            Subtype_Mark =>
655              New_Reference_To (Etype (Formal), Loc),
656            Name =>
657              Make_Explicit_Dereference (Loc,
658                Make_Selected_Component (Loc,
659                  Prefix =>
660                    Unchecked_Convert_To (Entry_Parameters_Type (Ent),
661                      Make_Identifier (Loc, Chars (Ptr))),
662                  Selector_Name =>
663                    New_Reference_To (Comp, Loc))));
664
665          Append (Decl, Decls);
666          Set_Renamed_Object (Formal, New_F);
667          Next_Formal (Formal);
668       end loop;
669    end Add_Formal_Renamings;
670
671    ------------------------
672    -- Add_Object_Pointer --
673    ------------------------
674
675    procedure Add_Object_Pointer
676      (Loc      : Source_Ptr;
677       Conc_Typ : Entity_Id;
678       Decls    : List_Id)
679    is
680       Rec_Typ : constant Entity_Id := Corresponding_Record_Type (Conc_Typ);
681       Decl    : Node_Id;
682       Obj_Ptr : Node_Id;
683
684    begin
685       --  Create the renaming declaration for the Protection object of a
686       --  protected type. _Object is used by Complete_Entry_Body.
687       --  ??? An attempt to make this a renaming was unsuccessful.
688
689       --  Build the entity for the access type
690
691       Obj_Ptr :=
692         Make_Defining_Identifier (Loc,
693           New_External_Name (Chars (Rec_Typ), 'P'));
694
695       --  Generate:
696       --    _object : poVP := poVP!O;
697
698       Decl :=
699         Make_Object_Declaration (Loc,
700           Defining_Identifier =>
701             Make_Defining_Identifier (Loc, Name_uObject),
702           Object_Definition =>
703             New_Reference_To (Obj_Ptr, Loc),
704           Expression =>
705             Unchecked_Convert_To (Obj_Ptr,
706               Make_Identifier (Loc, Name_uO)));
707       Set_Debug_Info_Needed (Defining_Identifier (Decl));
708       Prepend_To (Decls, Decl);
709
710       --  Generate:
711       --    type poVP is access poV;
712
713       Decl :=
714         Make_Full_Type_Declaration (Loc,
715           Defining_Identifier =>
716             Obj_Ptr,
717           Type_Definition =>
718             Make_Access_To_Object_Definition (Loc,
719           Subtype_Indication =>
720             New_Reference_To (Rec_Typ, Loc)));
721       Set_Debug_Info_Needed (Defining_Identifier (Decl));
722       Prepend_To (Decls, Decl);
723    end Add_Object_Pointer;
724
725    -----------------------
726    -- Build_Accept_Body --
727    -----------------------
728
729    function Build_Accept_Body (Astat : Node_Id) return  Node_Id is
730       Loc     : constant Source_Ptr := Sloc (Astat);
731       Stats   : constant Node_Id    := Handled_Statement_Sequence (Astat);
732       New_S   : Node_Id;
733       Hand    : Node_Id;
734       Call    : Node_Id;
735       Ohandle : Node_Id;
736
737    begin
738       --  At the end of the statement sequence, Complete_Rendezvous is called.
739       --  A label skipping the Complete_Rendezvous, and all other accept
740       --  processing, has already been added for the expansion of requeue
741       --  statements.
742
743       Call := Build_Runtime_Call (No_Location, RE_Complete_Rendezvous);
744       Insert_Before (Last (Statements (Stats)), Call);
745       Analyze (Call);
746
747       --  If exception handlers are present, then append Complete_Rendezvous
748       --  calls to the handlers, and construct the required outer block.
749
750       if Present (Exception_Handlers (Stats)) then
751          Hand := First (Exception_Handlers (Stats));
752
753          while Present (Hand) loop
754             Call := Build_Runtime_Call (No_Location, RE_Complete_Rendezvous);
755             Append (Call, Statements (Hand));
756             Analyze (Call);
757             Next (Hand);
758          end loop;
759
760          New_S :=
761            Make_Handled_Sequence_Of_Statements (Loc,
762              Statements => New_List (
763                Make_Block_Statement (Loc,
764                  Handled_Statement_Sequence => Stats)));
765
766       else
767          New_S := Stats;
768       end if;
769
770       --  At this stage we know that the new statement sequence does not
771       --  have an exception handler part, so we supply one to call
772       --  Exceptional_Complete_Rendezvous. This handler is
773
774       --    when all others =>
775       --       Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
776
777       --  We handle Abort_Signal to make sure that we properly catch the abort
778       --  case and wake up the caller.
779
780       Ohandle := Make_Others_Choice (Loc);
781       Set_All_Others (Ohandle);
782
783       Set_Exception_Handlers (New_S,
784         New_List (
785           Make_Implicit_Exception_Handler (Loc,
786             Exception_Choices => New_List (Ohandle),
787
788             Statements =>  New_List (
789               Make_Procedure_Call_Statement (No_Location,
790                 Name => New_Reference_To (
791                   RTE (RE_Exceptional_Complete_Rendezvous), No_Location),
792                 Parameter_Associations => New_List (
793                   Make_Function_Call (No_Location,
794                     Name => New_Reference_To (
795                       RTE (RE_Get_GNAT_Exception), No_Location))))))));
796
797       Set_Parent (New_S, Astat); -- temp parent for Analyze call
798       Analyze_Exception_Handlers (Exception_Handlers (New_S));
799       Expand_Exception_Handlers (New_S);
800
801       --  Exceptional_Complete_Rendezvous must be called with abort
802       --  still deferred, which is the case for a "when all others" handler.
803
804       return New_S;
805    end Build_Accept_Body;
806
807    -----------------------------------
808    -- Build_Activation_Chain_Entity --
809    -----------------------------------
810
811    procedure Build_Activation_Chain_Entity (N : Node_Id) is
812       P     : Node_Id;
813       Decls : List_Id;
814       Chain : Entity_Id;
815
816    begin
817       --  Loop to find enclosing construct containing activation chain variable
818
819       P := Parent (N);
820
821       while not Nkind_In (P, N_Subprogram_Body,
822                              N_Package_Declaration,
823                              N_Package_Body,
824                              N_Block_Statement,
825                              N_Task_Body,
826                              N_Extended_Return_Statement)
827       loop
828          P := Parent (P);
829       end loop;
830
831       --  If we are in a package body, the activation chain variable is
832       --  declared in the body, but the Activation_Chain_Entity is attached to
833       --  the spec.
834
835       if Nkind (P) = N_Package_Body then
836          Decls := Declarations (P);
837          P := Unit_Declaration_Node (Corresponding_Spec (P));
838
839       elsif Nkind (P) = N_Package_Declaration then
840          Decls := Visible_Declarations (Specification (P));
841
842       elsif Nkind (P) = N_Extended_Return_Statement then
843          Decls := Return_Object_Declarations (P);
844
845       else
846          Decls := Declarations (P);
847       end if;
848
849       --  If activation chain entity not already declared, declare it
850
851       if Nkind (P) = N_Extended_Return_Statement
852         or else No (Activation_Chain_Entity (P))
853       then
854          Chain := Make_Defining_Identifier (Sloc (N), Name_uChain);
855
856          --  Note: An extended return statement is not really a task activator,
857          --  but it does have an activation chain on which to store the tasks
858          --  temporarily. On successful return, the tasks on this chain are
859          --  moved to the chain passed in by the caller. We do not build an
860          --  Activation_Chain_Entity for an N_Extended_Return_Statement,
861          --  because we do not want to build a call to Activate_Tasks. Task
862          --  activation is the responsibility of the caller.
863
864          if Nkind (P) /= N_Extended_Return_Statement then
865             Set_Activation_Chain_Entity (P, Chain);
866          end if;
867
868          Prepend_To (Decls,
869            Make_Object_Declaration (Sloc (P),
870              Defining_Identifier => Chain,
871              Aliased_Present => True,
872              Object_Definition =>
873                New_Reference_To (RTE (RE_Activation_Chain), Sloc (P))));
874
875          Analyze (First (Decls));
876       end if;
877    end Build_Activation_Chain_Entity;
878
879    ----------------------------
880    -- Build_Barrier_Function --
881    ----------------------------
882
883    function Build_Barrier_Function
884      (N   : Node_Id;
885       Ent : Entity_Id;
886       Pid : Node_Id) return Node_Id
887    is
888       Loc         : constant Source_Ptr := Sloc (N);
889       Func_Id     : constant Entity_Id  := Barrier_Function (Ent);
890       Ent_Formals : constant Node_Id    := Entry_Body_Formal_Part (N);
891       Op_Decls    : constant List_Id    := New_List;
892       Func_Body   : Node_Id;
893
894    begin
895       --  Add a declaration for the Protection object, renaming declarations
896       --  for the discriminals and privals and finally a declaration for the
897       --  entry family index (if applicable).
898
899       Install_Private_Data_Declarations
900         (Loc, Func_Id, Pid, N, Op_Decls, True, Ekind (Ent) = E_Entry_Family);
901
902       --  Note: the condition in the barrier function needs to be properly
903       --  processed for the C/Fortran boolean possibility, but this happens
904       --  automatically since the return statement does this normalization.
905
906       Func_Body :=
907         Make_Subprogram_Body (Loc,
908           Specification =>
909             Build_Barrier_Function_Specification (Loc,
910               Make_Defining_Identifier (Loc, Chars (Func_Id))),
911           Declarations => Op_Decls,
912           Handled_Statement_Sequence =>
913             Make_Handled_Sequence_Of_Statements (Loc,
914               Statements => New_List (
915                 Make_Simple_Return_Statement (Loc,
916                   Expression => Condition (Ent_Formals)))));
917       Set_Is_Entry_Barrier_Function (Func_Body);
918
919       return Func_Body;
920    end Build_Barrier_Function;
921
922    ------------------------------------------
923    -- Build_Barrier_Function_Specification --
924    ------------------------------------------
925
926    function Build_Barrier_Function_Specification
927      (Loc    : Source_Ptr;
928       Def_Id : Entity_Id) return Node_Id
929    is
930    begin
931       Set_Debug_Info_Needed (Def_Id);
932
933       return Make_Function_Specification (Loc,
934         Defining_Unit_Name => Def_Id,
935         Parameter_Specifications => New_List (
936           Make_Parameter_Specification (Loc,
937             Defining_Identifier =>
938               Make_Defining_Identifier (Loc, Name_uO),
939             Parameter_Type =>
940               New_Reference_To (RTE (RE_Address), Loc)),
941
942           Make_Parameter_Specification (Loc,
943             Defining_Identifier =>
944               Make_Defining_Identifier (Loc, Name_uE),
945             Parameter_Type =>
946               New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))),
947
948         Result_Definition =>
949           New_Reference_To (Standard_Boolean, Loc));
950    end Build_Barrier_Function_Specification;
951
952    --------------------------
953    -- Build_Call_With_Task --
954    --------------------------
955
956    function Build_Call_With_Task
957      (N : Node_Id;
958       E : Entity_Id) return Node_Id
959    is
960       Loc : constant Source_Ptr := Sloc (N);
961    begin
962       return
963         Make_Function_Call (Loc,
964           Name => New_Reference_To (E, Loc),
965           Parameter_Associations => New_List (Concurrent_Ref (N)));
966    end Build_Call_With_Task;
967
968    --------------------------------
969    -- Build_Corresponding_Record --
970    --------------------------------
971
972    function Build_Corresponding_Record
973     (N    : Node_Id;
974      Ctyp : Entity_Id;
975      Loc  : Source_Ptr) return Node_Id
976    is
977       Rec_Ent  : constant Entity_Id :=
978                    Make_Defining_Identifier
979                      (Loc, New_External_Name (Chars (Ctyp), 'V'));
980       Disc     : Entity_Id;
981       Dlist    : List_Id;
982       New_Disc : Entity_Id;
983       Cdecls   : List_Id;
984
985    begin
986       Set_Corresponding_Record_Type     (Ctyp, Rec_Ent);
987       Set_Ekind                         (Rec_Ent, E_Record_Type);
988       Set_Has_Delayed_Freeze            (Rec_Ent, Has_Delayed_Freeze (Ctyp));
989       Set_Is_Concurrent_Record_Type     (Rec_Ent, True);
990       Set_Corresponding_Concurrent_Type (Rec_Ent, Ctyp);
991       Set_Stored_Constraint             (Rec_Ent, No_Elist);
992       Cdecls := New_List;
993
994       --  Use discriminals to create list of discriminants for record, and
995       --  create new discriminals for use in default expressions, etc. It is
996       --  worth noting that a task discriminant gives rise to 5 entities;
997
998       --  a) The original discriminant.
999       --  b) The discriminal for use in the task.
1000       --  c) The discriminant of the corresponding record.
1001       --  d) The discriminal for the init proc of the corresponding record.
1002       --  e) The local variable that renames the discriminant in the procedure
1003       --     for the task body.
1004
1005       --  In fact the discriminals b) are used in the renaming declarations
1006       --  for e). See details in  einfo (Handling of Discriminants).
1007
1008       if Present (Discriminant_Specifications (N)) then
1009          Dlist := New_List;
1010          Disc := First_Discriminant (Ctyp);
1011
1012          while Present (Disc) loop
1013             New_Disc := CR_Discriminant (Disc);
1014
1015             Append_To (Dlist,
1016               Make_Discriminant_Specification (Loc,
1017                 Defining_Identifier => New_Disc,
1018                 Discriminant_Type =>
1019                   New_Occurrence_Of (Etype (Disc), Loc),
1020                 Expression =>
1021                   New_Copy (Discriminant_Default_Value (Disc))));
1022
1023             Next_Discriminant (Disc);
1024          end loop;
1025
1026       else
1027          Dlist := No_List;
1028       end if;
1029
1030       --  Now we can construct the record type declaration. Note that this
1031       --  record is "limited tagged". It is "limited" to reflect the underlying
1032       --  limitedness of the task or protected object that it represents, and
1033       --  ensuring for example that it is properly passed by reference. It is
1034       --  "tagged" to give support to dispatching calls through interfaces (Ada
1035       --  2005: AI-345)
1036
1037       return
1038         Make_Full_Type_Declaration (Loc,
1039           Defining_Identifier => Rec_Ent,
1040           Discriminant_Specifications => Dlist,
1041           Type_Definition =>
1042             Make_Record_Definition (Loc,
1043               Component_List =>
1044                 Make_Component_List (Loc,
1045                   Component_Items => Cdecls),
1046               Tagged_Present  =>
1047                  Ada_Version >= Ada_05 and then Is_Tagged_Type (Ctyp),
1048               Limited_Present => True));
1049    end Build_Corresponding_Record;
1050
1051    ----------------------------------
1052    -- Build_Entry_Count_Expression --
1053    ----------------------------------
1054
1055    function Build_Entry_Count_Expression
1056      (Concurrent_Type : Node_Id;
1057       Component_List  : List_Id;
1058       Loc             : Source_Ptr) return Node_Id
1059    is
1060       Eindx  : Nat;
1061       Ent    : Entity_Id;
1062       Ecount : Node_Id;
1063       Comp   : Node_Id;
1064       Lo     : Node_Id;
1065       Hi     : Node_Id;
1066       Typ    : Entity_Id;
1067       Large  : Boolean;
1068
1069    begin
1070       --  Count number of non-family entries
1071
1072       Eindx := 0;
1073       Ent := First_Entity (Concurrent_Type);
1074       while Present (Ent) loop
1075          if Ekind (Ent) = E_Entry then
1076             Eindx := Eindx + 1;
1077          end if;
1078
1079          Next_Entity (Ent);
1080       end loop;
1081
1082       Ecount := Make_Integer_Literal (Loc, Eindx);
1083
1084       --  Loop through entry families building the addition nodes
1085
1086       Ent := First_Entity (Concurrent_Type);
1087       Comp := First (Component_List);
1088       while Present (Ent) loop
1089          if Ekind (Ent) = E_Entry_Family then
1090             while Chars (Ent) /= Chars (Defining_Identifier (Comp)) loop
1091                Next (Comp);
1092             end loop;
1093
1094             Typ := Etype (Discrete_Subtype_Definition (Parent (Ent)));
1095             Hi := Type_High_Bound (Typ);
1096             Lo := Type_Low_Bound  (Typ);
1097             Large := Is_Potentially_Large_Family
1098                        (Base_Type (Typ), Concurrent_Type, Lo, Hi);
1099             Ecount :=
1100               Make_Op_Add (Loc,
1101                 Left_Opnd  => Ecount,
1102                 Right_Opnd => Family_Size
1103                                 (Loc, Hi, Lo, Concurrent_Type, Large));
1104          end if;
1105
1106          Next_Entity (Ent);
1107       end loop;
1108
1109       return Ecount;
1110    end Build_Entry_Count_Expression;
1111
1112    -----------------------
1113    -- Build_Entry_Names --
1114    -----------------------
1115
1116    function Build_Entry_Names (Conc_Typ : Entity_Id) return Node_Id is
1117       Loc       : constant Source_Ptr := Sloc (Conc_Typ);
1118       B_Decls   : List_Id;
1119       B_Stmts   : List_Id;
1120       Comp      : Node_Id;
1121       Index     : Entity_Id;
1122       Index_Typ : RE_Id;
1123       Typ       : Entity_Id := Conc_Typ;
1124
1125       procedure Build_Entry_Family_Name (Id : Entity_Id);
1126       --  Generate:
1127       --    for Lnn in Family_Low .. Family_High loop
1128       --       Inn := Inn + 1;
1129       --       Set_Entry_Name
1130       --         (_init._object, Inn, new String ("<Entry name> " & Lnn'Img));
1131       --          _init._task_id
1132       --    end loop;
1133       --  Note that the bounds of the range may reference discriminants. The
1134       --  above construct is added directly to the statements of the block.
1135
1136       procedure Build_Entry_Name (Id : Entity_Id);
1137       --  Generate:
1138       --    Inn := Inn + 1;
1139       --    Set_Entry_Name (_init._task_id, Inn, new String ("<Entry name>");
1140       --                    _init._object
1141       --  The above construct is added directly to the statements of the block.
1142
1143       function Build_Set_Entry_Name_Call (Arg3 : Node_Id) return Node_Id;
1144       --  Generate the call to the runtime routine Set_Entry_Name with actuals
1145       --  _init._task_id or _init._object, Inn and Arg3.
1146
1147       function Find_Protection_Type (Conc_Typ : Entity_Id) return Entity_Id;
1148       --  Given a protected type or its corresponding record, find the type of
1149       --  field _object.
1150
1151       procedure Increment_Index (Stmts : List_Id);
1152       --  Generate the following and add it to Stmts
1153       --    Inn := Inn + 1;
1154
1155       -----------------------------
1156       -- Build_Entry_Family_Name --
1157       -----------------------------
1158
1159       procedure Build_Entry_Family_Name (Id : Entity_Id) is
1160          Def     : constant Node_Id :=
1161                      Discrete_Subtype_Definition (Parent (Id));
1162          L_Id    : constant Entity_Id :=
1163                      Make_Defining_Identifier (Loc, New_Internal_Name ('L'));
1164          L_Stmts : constant List_Id := New_List;
1165          Val     : Node_Id;
1166
1167          function Build_Range (Def : Node_Id) return Node_Id;
1168          --  Given a discrete subtype definition of an entry family, generate a
1169          --  range node which covers the range of Def's type.
1170
1171          -----------------
1172          -- Build_Range --
1173          -----------------
1174
1175          function Build_Range (Def : Node_Id) return Node_Id is
1176             High : Node_Id := Type_High_Bound (Etype (Def));
1177             Low  : Node_Id := Type_Low_Bound  (Etype (Def));
1178
1179          begin
1180             --  If a bound references a discriminant, generate an identifier
1181             --  with the same name. Resolution will map it to the formals of
1182             --  the init proc.
1183
1184             if Is_Entity_Name (Low)
1185               and then Ekind (Entity (Low)) = E_Discriminant
1186             then
1187                Low := Make_Identifier (Loc, Chars (Low));
1188             else
1189                Low := New_Copy_Tree (Low);
1190             end if;
1191
1192             if Is_Entity_Name (High)
1193               and then Ekind (Entity (High)) = E_Discriminant
1194             then
1195                High := Make_Identifier (Loc, Chars (High));
1196             else
1197                High := New_Copy_Tree (High);
1198             end if;
1199
1200             return
1201               Make_Range (Loc,
1202                 Low_Bound  => Low,
1203                 High_Bound => High);
1204          end Build_Range;
1205
1206       --  Start of processing for Build_Entry_Family_Name
1207
1208       begin
1209          Get_Name_String (Chars (Id));
1210
1211          if Is_Enumeration_Type (Etype (Def)) then
1212             Name_Len := Name_Len + 1;
1213             Name_Buffer (Name_Len) := ' ';
1214          end if;
1215
1216          --  Generate:
1217          --    new String'("<Entry name>" & Lnn'Img);
1218
1219          Val :=
1220            Make_Allocator (Loc,
1221              Make_Qualified_Expression (Loc,
1222                Subtype_Mark =>
1223                  New_Reference_To (Standard_String, Loc),
1224                Expression =>
1225                  Make_Op_Concat (Loc,
1226                    Left_Opnd =>
1227                      Make_String_Literal (Loc,
1228                        String_From_Name_Buffer),
1229                    Right_Opnd =>
1230                      Make_Attribute_Reference (Loc,
1231                        Prefix =>
1232                          New_Reference_To (L_Id, Loc),
1233                            Attribute_Name => Name_Img))));
1234
1235          Increment_Index (L_Stmts);
1236          Append_To (L_Stmts, Build_Set_Entry_Name_Call (Val));
1237
1238          --  Generate:
1239          --    for Lnn in Family_Low .. Family_High loop
1240          --       Inn := Inn + 1;
1241          --       Set_Entry_Name (_init._task_id, Inn, <Val>);
1242          --    end loop;
1243
1244          Append_To (B_Stmts,
1245            Make_Loop_Statement (Loc,
1246              Iteration_Scheme =>
1247                Make_Iteration_Scheme (Loc,
1248                  Loop_Parameter_Specification =>
1249                    Make_Loop_Parameter_Specification (Loc,
1250                     Defining_Identifier => L_Id,
1251                     Discrete_Subtype_Definition =>
1252                       Build_Range (Def))),
1253              Statements => L_Stmts,
1254              End_Label => Empty));
1255       end Build_Entry_Family_Name;
1256
1257       ----------------------
1258       -- Build_Entry_Name --
1259       ----------------------
1260
1261       procedure Build_Entry_Name (Id : Entity_Id) is
1262          Val : Node_Id;
1263
1264       begin
1265          Get_Name_String (Chars (Id));
1266          Val :=
1267            Make_Allocator (Loc,
1268              Make_Qualified_Expression (Loc,
1269                Subtype_Mark =>
1270                  New_Reference_To (Standard_String, Loc),
1271                Expression =>
1272                  Make_String_Literal (Loc,
1273                    String_From_Name_Buffer)));
1274
1275          Increment_Index (B_Stmts);
1276          Append_To (B_Stmts, Build_Set_Entry_Name_Call (Val));
1277       end Build_Entry_Name;
1278
1279       -------------------------------
1280       -- Build_Set_Entry_Name_Call --
1281       -------------------------------
1282
1283       function Build_Set_Entry_Name_Call (Arg3 : Node_Id) return Node_Id is
1284          Arg1 : Name_Id;
1285          Proc : RE_Id;
1286
1287       begin
1288          --  Determine the proper name for the first argument and the RTS
1289          --  routine to call.
1290
1291          if Is_Protected_Type (Typ) then
1292             Arg1 := Name_uObject;
1293             Proc := RO_PE_Set_Entry_Name;
1294
1295          else pragma Assert (Is_Task_Type (Typ));
1296             Arg1 := Name_uTask_Id;
1297             Proc := RO_TS_Set_Entry_Name;
1298          end if;
1299
1300          --  Generate:
1301          --    Set_Entry_Name (_init.Arg1, Inn, Arg3);
1302
1303          return
1304            Make_Procedure_Call_Statement (Loc,
1305              Name =>
1306                New_Reference_To (RTE (Proc), Loc),
1307              Parameter_Associations => New_List (
1308                Make_Selected_Component (Loc,              --  _init._object
1309                  Prefix =>                                --  _init._task_id
1310                    Make_Identifier (Loc, Name_uInit),
1311                  Selector_Name =>
1312                    Make_Identifier (Loc, Arg1)),
1313                New_Reference_To (Index, Loc),             --  Inn
1314                Arg3));                                    --  Val
1315       end Build_Set_Entry_Name_Call;
1316
1317       --------------------------
1318       -- Find_Protection_Type --
1319       --------------------------
1320
1321       function Find_Protection_Type (Conc_Typ : Entity_Id) return Entity_Id is
1322          Comp : Entity_Id;
1323          Typ  : Entity_Id := Conc_Typ;
1324
1325       begin
1326          if Is_Concurrent_Type (Typ) then
1327             Typ := Corresponding_Record_Type (Typ);
1328          end if;
1329
1330          Comp := First_Component (Typ);
1331          while Present (Comp) loop
1332             if Chars (Comp) = Name_uObject then
1333                return Base_Type (Etype (Comp));
1334             end if;
1335
1336             Next_Component (Comp);
1337          end loop;
1338
1339          --  The corresponding record of a protected type should always have an
1340          --  _object field.
1341
1342          raise Program_Error;
1343       end Find_Protection_Type;
1344
1345       ---------------------
1346       -- Increment_Index --
1347       ---------------------
1348
1349       procedure Increment_Index (Stmts : List_Id) is
1350       begin
1351          --  Generate:
1352          --    Inn := Inn + 1;
1353
1354          Append_To (Stmts,
1355            Make_Assignment_Statement (Loc,
1356              Name =>
1357                New_Reference_To (Index, Loc),
1358              Expression =>
1359                Make_Op_Add (Loc,
1360                  Left_Opnd =>
1361                    New_Reference_To (Index, Loc),
1362                  Right_Opnd =>
1363                    Make_Integer_Literal (Loc, 1))));
1364       end Increment_Index;
1365
1366    --  Start of processing for Build_Entry_Names
1367
1368    begin
1369       --  Retrieve the original concurrent type
1370
1371       if Is_Concurrent_Record_Type (Typ) then
1372          Typ := Corresponding_Concurrent_Type (Typ);
1373       end if;
1374
1375       pragma Assert (Is_Protected_Type (Typ) or else Is_Task_Type (Typ));
1376
1377       --  Nothing to do if the type has no entries
1378
1379       if not Has_Entries (Typ) then
1380          return Empty;
1381       end if;
1382
1383       --  Avoid generating entry names for a protected type with only one entry
1384
1385       if Is_Protected_Type (Typ)
1386         and then Find_Protection_Type (Typ) /= RTE (RE_Protection_Entries)
1387       then
1388          return Empty;
1389       end if;
1390
1391       Index := Make_Defining_Identifier (Loc, New_Internal_Name ('I'));
1392
1393       --  Step 1: Generate the declaration of the index variable:
1394       --    Inn : Protected_Entry_Index := 0;
1395       --      or
1396       --    Inn : Task_Entry_Index := 0;
1397
1398       if Is_Protected_Type (Typ) then
1399          Index_Typ := RE_Protected_Entry_Index;
1400       else
1401          Index_Typ := RE_Task_Entry_Index;
1402       end if;
1403
1404       B_Decls := New_List;
1405       Append_To (B_Decls,
1406         Make_Object_Declaration (Loc,
1407           Defining_Identifier => Index,
1408           Object_Definition =>
1409             New_Reference_To (RTE (Index_Typ), Loc),
1410           Expression =>
1411             Make_Integer_Literal (Loc, 0)));
1412
1413       B_Stmts := New_List;
1414
1415       --  Step 2: Generate a call to Set_Entry_Name for each entry and entry
1416       --  family member.
1417
1418       Comp := First_Entity (Typ);
1419       while Present (Comp) loop
1420          if Ekind (Comp) = E_Entry then
1421             Build_Entry_Name (Comp);
1422
1423          elsif Ekind (Comp) = E_Entry_Family then
1424             Build_Entry_Family_Name (Comp);
1425          end if;
1426
1427          Next_Entity (Comp);
1428       end loop;
1429
1430       --  Step 3: Wrap the statements in a block
1431
1432       return
1433         Make_Block_Statement (Loc,
1434           Declarations => B_Decls,
1435           Handled_Statement_Sequence =>
1436             Make_Handled_Sequence_Of_Statements (Loc,
1437               Statements => B_Stmts));
1438    end Build_Entry_Names;
1439
1440    ---------------------------
1441    -- Build_Parameter_Block --
1442    ---------------------------
1443
1444    function Build_Parameter_Block
1445      (Loc     : Source_Ptr;
1446       Actuals : List_Id;
1447       Formals : List_Id;
1448       Decls   : List_Id) return Entity_Id
1449    is
1450       Actual   : Entity_Id;
1451       Comp_Nam : Node_Id;
1452       Comps    : List_Id;
1453       Formal   : Entity_Id;
1454       Has_Comp : Boolean := False;
1455       Rec_Nam  : Node_Id;
1456
1457    begin
1458       Actual := First (Actuals);
1459       Comps  := New_List;
1460       Formal := Defining_Identifier (First (Formals));
1461
1462       while Present (Actual) loop
1463          if not Is_Controlling_Actual (Actual) then
1464
1465             --  Generate:
1466             --    type Ann is access all <actual-type>
1467
1468             Comp_Nam :=
1469               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
1470
1471             Append_To (Decls,
1472               Make_Full_Type_Declaration (Loc,
1473                 Defining_Identifier =>
1474                   Comp_Nam,
1475                 Type_Definition =>
1476                   Make_Access_To_Object_Definition (Loc,
1477                     All_Present =>
1478                       True,
1479                     Constant_Present =>
1480                       Ekind (Formal) = E_In_Parameter,
1481                     Subtype_Indication =>
1482                       New_Reference_To (Etype (Actual), Loc))));
1483
1484             --  Generate:
1485             --    Param : Ann;
1486
1487             Append_To (Comps,
1488               Make_Component_Declaration (Loc,
1489                 Defining_Identifier =>
1490                   Make_Defining_Identifier (Loc, Chars (Formal)),
1491                 Component_Definition =>
1492                   Make_Component_Definition (Loc,
1493                     Aliased_Present =>
1494                       False,
1495                     Subtype_Indication =>
1496                       New_Reference_To (Comp_Nam, Loc))));
1497
1498             Has_Comp := True;
1499          end if;
1500
1501          Next_Actual (Actual);
1502          Next_Formal_With_Extras (Formal);
1503       end loop;
1504
1505       Rec_Nam :=
1506         Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
1507
1508       if Has_Comp then
1509
1510          --  Generate:
1511          --    type Pnn is record
1512          --       Param1 : Ann1;
1513          --       ...
1514          --       ParamN : AnnN;
1515
1516          --  where Pnn is a parameter wrapping record, Param1 .. ParamN are
1517          --  the original parameter names and Ann1 .. AnnN are the access to
1518          --  actual types.
1519
1520          Append_To (Decls,
1521            Make_Full_Type_Declaration (Loc,
1522              Defining_Identifier =>
1523                Rec_Nam,
1524              Type_Definition =>
1525                Make_Record_Definition (Loc,
1526                  Component_List =>
1527                    Make_Component_List (Loc, Comps))));
1528       else
1529          --  Generate:
1530          --    type Pnn is null record;
1531
1532          Append_To (Decls,
1533            Make_Full_Type_Declaration (Loc,
1534              Defining_Identifier =>
1535                Rec_Nam,
1536              Type_Definition =>
1537                Make_Record_Definition (Loc,
1538                  Null_Present   => True,
1539                  Component_List => Empty)));
1540       end if;
1541
1542       return Rec_Nam;
1543    end Build_Parameter_Block;
1544
1545    --------------------------
1546    -- Build_Wrapper_Bodies --
1547    --------------------------
1548
1549    procedure Build_Wrapper_Bodies
1550      (Loc : Source_Ptr;
1551       Typ : Entity_Id;
1552       N   : Node_Id)
1553    is
1554       Rec_Typ : Entity_Id;
1555
1556       function Build_Wrapper_Body
1557         (Loc     : Source_Ptr;
1558          Subp_Id : Entity_Id;
1559          Obj_Typ : Entity_Id;
1560          Formals : List_Id) return Node_Id;
1561       --  Ada 2005 (AI-345): Build the body that wraps a primitive operation
1562       --  associated with a protected or task type. Subp_Id is the subprogram
1563       --  name which will be wrapped. Obj_Typ is the type of the new formal
1564       --  parameter which handles dispatching and object notation. Formals are
1565       --  the original formals of Subp_Id which will be explicitly replicated.
1566
1567       ------------------------
1568       -- Build_Wrapper_Body --
1569       ------------------------
1570
1571       function Build_Wrapper_Body
1572         (Loc     : Source_Ptr;
1573          Subp_Id : Entity_Id;
1574          Obj_Typ : Entity_Id;
1575          Formals : List_Id) return Node_Id
1576       is
1577          Body_Spec : Node_Id;
1578
1579       begin
1580          Body_Spec := Build_Wrapper_Spec (Loc, Subp_Id, Obj_Typ, Formals);
1581
1582          --  The subprogram is not overriding or is not a primitive declared
1583          --  between two views.
1584
1585          if No (Body_Spec) then
1586             return Empty;
1587          end if;
1588
1589          declare
1590             Actuals      : List_Id := No_List;
1591             Conv_Id      : Node_Id;
1592             First_Formal : Node_Id;
1593             Formal       : Node_Id;
1594             Nam          : Node_Id;
1595
1596          begin
1597             --  Map formals to actuals. Use the list built for the wrapper
1598             --  spec, skipping the object notation parameter.
1599
1600             First_Formal := First (Parameter_Specifications (Body_Spec));
1601
1602             Formal := First_Formal;
1603             Next (Formal);
1604
1605             if Present (Formal) then
1606                Actuals := New_List;
1607
1608                while Present (Formal) loop
1609                   Append_To (Actuals,
1610                     Make_Identifier (Loc, Chars =>
1611                       Chars (Defining_Identifier (Formal))));
1612
1613                   Next (Formal);
1614                end loop;
1615             end if;
1616
1617             --  Special processing for primitives declared between a private
1618             --  type and its completion.
1619
1620             if Is_Private_Primitive_Subprogram (Subp_Id) then
1621                if No (Actuals) then
1622                   Actuals := New_List;
1623                end if;
1624
1625                Prepend_To (Actuals,
1626                  Unchecked_Convert_To (
1627                    Corresponding_Concurrent_Type (Obj_Typ),
1628                    Make_Identifier (Loc, Name_uO)));
1629
1630                Nam := New_Reference_To (Subp_Id, Loc);
1631
1632             else
1633                --  An access-to-variable object parameter requires an explicit
1634                --  dereference in the unchecked conversion. This case occurs
1635                --  when a protected entry wrapper must override an interface
1636                --  level procedure with interface access as first parameter.
1637
1638                --     O.all.Subp_Id (Formal_1, ..., Formal_N)
1639
1640                if Nkind (Parameter_Type (First_Formal)) =
1641                     N_Access_Definition
1642                then
1643                   Conv_Id :=
1644                     Make_Explicit_Dereference (Loc,
1645                       Prefix => Make_Identifier (Loc, Name_uO));
1646                else
1647                   Conv_Id := Make_Identifier (Loc, Name_uO);
1648                end if;
1649
1650                Nam :=
1651                  Make_Selected_Component (Loc,
1652                    Prefix =>
1653                      Unchecked_Convert_To (
1654                        Corresponding_Concurrent_Type (Obj_Typ),
1655                        Conv_Id),
1656                    Selector_Name =>
1657                      New_Reference_To (Subp_Id, Loc));
1658             end if;
1659
1660             --  Create the subprogram body
1661
1662             if Ekind (Subp_Id) = E_Function then
1663                return
1664                  Make_Subprogram_Body (Loc,
1665                    Specification              => Body_Spec,
1666                    Declarations               => Empty_List,
1667                    Handled_Statement_Sequence =>
1668                      Make_Handled_Sequence_Of_Statements (Loc,
1669                        Statements => New_List (
1670                          Make_Simple_Return_Statement (Loc,
1671                            Make_Function_Call (Loc,
1672                              Name                   => Nam,
1673                              Parameter_Associations => Actuals)))));
1674
1675             else
1676                return
1677                  Make_Subprogram_Body (Loc,
1678                    Specification              => Body_Spec,
1679                    Declarations               => Empty_List,
1680                    Handled_Statement_Sequence =>
1681                      Make_Handled_Sequence_Of_Statements (Loc,
1682                        Statements => New_List (
1683                          Make_Procedure_Call_Statement (Loc,
1684                            Name                   => Nam,
1685                            Parameter_Associations => Actuals))));
1686             end if;
1687          end;
1688       end Build_Wrapper_Body;
1689
1690    --  Start of processing for Build_Wrapper_Bodies
1691
1692    begin
1693       if Is_Concurrent_Type (Typ) then
1694          Rec_Typ := Corresponding_Record_Type (Typ);
1695       else
1696          Rec_Typ := Typ;
1697       end if;
1698
1699       --  Generate wrapper bodies for a concurrent type which implements an
1700       --  interface.
1701
1702       if Present (Interfaces (Rec_Typ)) then
1703          declare
1704             Insert_Nod : Node_Id;
1705             Prim       : Entity_Id;
1706             Prim_Elmt  : Elmt_Id;
1707             Prim_Decl  : Node_Id;
1708             Subp       : Entity_Id;
1709             Wrap_Body  : Node_Id;
1710             Wrap_Id    : Entity_Id;
1711
1712          begin
1713             Insert_Nod := N;
1714
1715             --  Examine all primitive operations of the corresponding record
1716             --  type, looking for wrapper specs. Generate bodies in order to
1717             --  complete them.
1718
1719             Prim_Elmt := First_Elmt (Primitive_Operations (Rec_Typ));
1720             while Present (Prim_Elmt) loop
1721                Prim := Node (Prim_Elmt);
1722
1723                if (Ekind (Prim) = E_Function
1724                      or else Ekind (Prim) = E_Procedure)
1725                  and then Is_Primitive_Wrapper (Prim)
1726                then
1727                   Subp := Wrapped_Entity (Prim);
1728                   Prim_Decl := Parent (Parent (Prim));
1729
1730                   Wrap_Body :=
1731                     Build_Wrapper_Body (Loc,
1732                       Subp_Id => Subp,
1733                       Obj_Typ => Rec_Typ,
1734                       Formals => Parameter_Specifications (Parent (Subp)));
1735                   Wrap_Id := Defining_Unit_Name (Specification (Wrap_Body));
1736
1737                   Set_Corresponding_Spec (Wrap_Body, Prim);
1738                   Set_Corresponding_Body (Prim_Decl, Wrap_Id);
1739
1740                   Insert_After (Insert_Nod, Wrap_Body);
1741                   Insert_Nod := Wrap_Body;
1742
1743                   Analyze (Wrap_Body);
1744                end if;
1745
1746                Next_Elmt (Prim_Elmt);
1747             end loop;
1748          end;
1749       end if;
1750    end Build_Wrapper_Bodies;
1751
1752    ------------------------
1753    -- Build_Wrapper_Spec --
1754    ------------------------
1755
1756    function Build_Wrapper_Spec
1757      (Loc     : Source_Ptr;
1758       Subp_Id : Entity_Id;
1759       Obj_Typ : Entity_Id;
1760       Formals : List_Id) return Node_Id
1761    is
1762       First_Param   : Node_Id;
1763       Iface         : Entity_Id;
1764       Iface_Elmt    : Elmt_Id;
1765       Iface_Op      : Entity_Id;
1766       Iface_Op_Elmt : Elmt_Id;
1767
1768       function Overriding_Possible
1769         (Iface_Op : Entity_Id;
1770          Wrapper  : Entity_Id) return Boolean;
1771       --  Determine whether a primitive operation can be overridden by Wrapper.
1772       --  Iface_Op is the candidate primitive operation of an interface type,
1773       --  Wrapper is the generated entry wrapper.
1774
1775       function Replicate_Formals
1776         (Loc     : Source_Ptr;
1777          Formals : List_Id) return List_Id;
1778       --  An explicit parameter replication is required due to the Is_Entry_
1779       --  Formal flag being set for all the formals of an entry. The explicit
1780       --  replication removes the flag that would otherwise cause a different
1781       --  path of analysis.
1782
1783       -------------------------
1784       -- Overriding_Possible --
1785       -------------------------
1786
1787       function Overriding_Possible
1788         (Iface_Op : Entity_Id;
1789          Wrapper  : Entity_Id) return Boolean
1790       is
1791          Iface_Op_Spec : constant Node_Id := Parent (Iface_Op);
1792          Wrapper_Spec  : constant Node_Id := Parent (Wrapper);
1793
1794          function Type_Conformant_Parameters
1795            (Iface_Op_Params : List_Id;
1796             Wrapper_Params  : List_Id) return Boolean;
1797          --  Determine whether the parameters of the generated entry wrapper
1798          --  and those of a primitive operation are type conformant. During
1799          --  this check, the first parameter of the primitive operation is
1800          --  always skipped.
1801
1802          --------------------------------
1803          -- Type_Conformant_Parameters --
1804          --------------------------------
1805
1806          function Type_Conformant_Parameters
1807            (Iface_Op_Params : List_Id;
1808             Wrapper_Params  : List_Id) return Boolean
1809          is
1810             Iface_Op_Param : Node_Id;
1811             Iface_Op_Typ   : Entity_Id;
1812             Wrapper_Param  : Node_Id;
1813             Wrapper_Typ    : Entity_Id;
1814
1815          begin
1816             --  Skip the first parameter of the primitive operation
1817
1818             Iface_Op_Param := Next (First (Iface_Op_Params));
1819             Wrapper_Param  := First (Wrapper_Params);
1820             while Present (Iface_Op_Param)
1821               and then Present (Wrapper_Param)
1822             loop
1823                Iface_Op_Typ := Find_Parameter_Type (Iface_Op_Param);
1824                Wrapper_Typ  := Find_Parameter_Type (Wrapper_Param);
1825
1826                --  The two parameters must be mode conformant
1827
1828                if not Conforming_Types
1829                         (Iface_Op_Typ, Wrapper_Typ, Mode_Conformant)
1830                then
1831                   return False;
1832                end if;
1833
1834                Next (Iface_Op_Param);
1835                Next (Wrapper_Param);
1836             end loop;
1837
1838             --  One of the lists is longer than the other
1839
1840             if Present (Iface_Op_Param) or else Present (Wrapper_Param) then
1841                return False;
1842             end if;
1843
1844             return True;
1845          end Type_Conformant_Parameters;
1846
1847       --  Start of processing for Overriding_Possible
1848
1849       begin
1850          if Chars (Iface_Op) /= Chars (Wrapper) then
1851             return False;
1852          end if;
1853
1854          --  If an inherited subprogram is implemented by a protected procedure
1855          --  or an entry, then the first parameter of the inherited subprogram
1856          --  shall be of mode OUT or IN OUT, or access-to-variable parameter.
1857
1858          if Ekind (Iface_Op) = E_Procedure
1859            and then Present (Parameter_Specifications (Iface_Op_Spec))
1860          then
1861             declare
1862                Obj_Param : constant Node_Id :=
1863                              First (Parameter_Specifications (Iface_Op_Spec));
1864             begin
1865                if not Out_Present (Obj_Param)
1866                  and then Nkind (Parameter_Type (Obj_Param)) /=
1867                                                          N_Access_Definition
1868                then
1869                   return False;
1870                end if;
1871             end;
1872          end if;
1873
1874          return
1875            Type_Conformant_Parameters (
1876              Parameter_Specifications (Iface_Op_Spec),
1877              Parameter_Specifications (Wrapper_Spec));
1878       end Overriding_Possible;
1879
1880       -----------------------
1881       -- Replicate_Formals --
1882       -----------------------
1883
1884       function Replicate_Formals
1885         (Loc     : Source_Ptr;
1886          Formals : List_Id) return List_Id
1887       is
1888          New_Formals : constant List_Id := New_List;
1889          Formal      : Node_Id;
1890          Param_Type  : Node_Id;
1891
1892       begin
1893          Formal := First (Formals);
1894
1895          --  Skip the object parameter when dealing with primitives declared
1896          --  between two views.
1897
1898          if Is_Private_Primitive_Subprogram (Subp_Id) then
1899             Formal := Next (Formal);
1900          end if;
1901
1902          while Present (Formal) loop
1903
1904             --  Create an explicit copy of the entry parameter
1905
1906             --  When creating the wrapper subprogram for a primitive operation
1907             --  of a protected interface we must construct an equivalent
1908             --  signature to that of the overriding operation. For regular
1909             --  parameters we can just use the type of the formal, but for
1910             --  access to subprogram parameters we need to reanalyze the
1911             --  parameter type to create local entities for the signature of
1912             --  the subprogram type. Using the entities of the overriding
1913             --  subprogram will result in out-of-scope errors in the back-end.
1914
1915             if Nkind (Parameter_Type (Formal)) = N_Access_Definition then
1916                Param_Type := Copy_Separate_Tree (Parameter_Type (Formal));
1917             else
1918                Param_Type :=
1919                  New_Reference_To (Etype (Parameter_Type (Formal)), Loc);
1920             end if;
1921
1922             Append_To (New_Formals,
1923               Make_Parameter_Specification (Loc,
1924                 Defining_Identifier =>
1925                   Make_Defining_Identifier (Loc,
1926                     Chars          => Chars (Defining_Identifier (Formal))),
1927                     In_Present     => In_Present  (Formal),
1928                     Out_Present    => Out_Present (Formal),
1929                     Parameter_Type => Param_Type));
1930
1931             Next (Formal);
1932          end loop;
1933
1934          return New_Formals;
1935       end Replicate_Formals;
1936
1937    --  Start of processing for Build_Wrapper_Spec
1938
1939    begin
1940       --  There is no point in building wrappers for non-tagged concurrent
1941       --  types.
1942
1943       pragma Assert (Is_Tagged_Type (Obj_Typ));
1944
1945       --  An entry or a protected procedure can override a routine where the
1946       --  controlling formal is either IN OUT, OUT or is of access-to-variable
1947       --  type. Since the wrapper must have the exact same signature as that of
1948       --  the overridden subprogram, we try to find the overriding candidate
1949       --  and use its controlling formal.
1950
1951       First_Param := Empty;
1952
1953       --  Check every implemented interface
1954
1955       if Present (Interfaces (Obj_Typ)) then
1956          Iface_Elmt := First_Elmt (Interfaces (Obj_Typ));
1957          Search : while Present (Iface_Elmt) loop
1958             Iface := Node (Iface_Elmt);
1959
1960             --  Check every interface primitive
1961
1962             if Present (Primitive_Operations (Iface)) then
1963                Iface_Op_Elmt := First_Elmt (Primitive_Operations (Iface));
1964                while Present (Iface_Op_Elmt) loop
1965                   Iface_Op := Node (Iface_Op_Elmt);
1966
1967                   --  Ignore predefined primitives
1968
1969                   if not Is_Predefined_Dispatching_Operation (Iface_Op) then
1970                      Iface_Op := Ultimate_Alias (Iface_Op);
1971
1972                      --  The current primitive operation can be overridden by
1973                      --  the generated entry wrapper.
1974
1975                      if Overriding_Possible (Iface_Op, Subp_Id) then
1976                         First_Param :=
1977                           First (Parameter_Specifications (Parent (Iface_Op)));
1978
1979                         exit Search;
1980                      end if;
1981                   end if;
1982
1983                   Next_Elmt (Iface_Op_Elmt);
1984                end loop;
1985             end if;
1986
1987             Next_Elmt (Iface_Elmt);
1988          end loop Search;
1989       end if;
1990
1991       --  If the subprogram to be wrapped is not overriding anything or is not
1992       --  a primitive declared between two views, do not produce anything. This
1993       --  avoids spurious errors involving overriding.
1994
1995       if No (First_Param)
1996         and then not Is_Private_Primitive_Subprogram (Subp_Id)
1997       then
1998          return Empty;
1999       end if;
2000
2001       declare
2002          Wrapper_Id    : constant Entity_Id :=
2003                            Make_Defining_Identifier (Loc, Chars (Subp_Id));
2004          New_Formals   : List_Id;
2005          Obj_Param     : Node_Id;
2006          Obj_Param_Typ : Entity_Id;
2007
2008       begin
2009          --  Minimum decoration is needed to catch the entity in
2010          --  Sem_Ch6.Override_Dispatching_Operation.
2011
2012          if Ekind (Subp_Id) = E_Function then
2013             Set_Ekind (Wrapper_Id, E_Function);
2014          else
2015             Set_Ekind (Wrapper_Id, E_Procedure);
2016          end if;
2017
2018          Set_Is_Primitive_Wrapper (Wrapper_Id);
2019          Set_Wrapped_Entity       (Wrapper_Id, Subp_Id);
2020          Set_Is_Private_Primitive (Wrapper_Id,
2021            Is_Private_Primitive_Subprogram (Subp_Id));
2022
2023          --  Process the formals
2024
2025          New_Formals := Replicate_Formals (Loc, Formals);
2026
2027          --  Routine Subp_Id has been found to override an interface primitive.
2028          --  If the interface operation has an access parameter, create a copy
2029          --  of it, with the same null exclusion indicator if present.
2030
2031          if Present (First_Param) then
2032             if Nkind (Parameter_Type (First_Param)) = N_Access_Definition then
2033                Obj_Param_Typ :=
2034                  Make_Access_Definition (Loc,
2035                    Subtype_Mark =>
2036                      New_Reference_To (Obj_Typ, Loc));
2037                Set_Null_Exclusion_Present (Obj_Param_Typ,
2038                  Null_Exclusion_Present (Parameter_Type (First_Param)));
2039
2040             else
2041                Obj_Param_Typ := New_Reference_To (Obj_Typ, Loc);
2042             end if;
2043
2044             Obj_Param :=
2045               Make_Parameter_Specification (Loc,
2046                 Defining_Identifier =>
2047                   Make_Defining_Identifier (Loc,
2048                     Chars => Name_uO),
2049                 In_Present          => In_Present  (First_Param),
2050                 Out_Present         => Out_Present (First_Param),
2051                 Parameter_Type      => Obj_Param_Typ);
2052
2053          --  If we are dealing with a primitive declared between two views,
2054          --  create a default parameter.
2055
2056          else pragma Assert (Is_Private_Primitive_Subprogram (Subp_Id));
2057             Obj_Param :=
2058               Make_Parameter_Specification (Loc,
2059                 Defining_Identifier =>
2060                   Make_Defining_Identifier (Loc, Name_uO),
2061                 In_Present => True,
2062                 Out_Present => Ekind (Subp_Id) /= E_Function,
2063                   Parameter_Type => New_Reference_To (Obj_Typ, Loc));
2064          end if;
2065
2066          Prepend_To (New_Formals, Obj_Param);
2067
2068          --  Build the final spec
2069
2070          if Ekind (Subp_Id) = E_Function then
2071             return
2072               Make_Function_Specification (Loc,
2073                 Defining_Unit_Name       => Wrapper_Id,
2074                 Parameter_Specifications => New_Formals,
2075                 Result_Definition        =>
2076                   New_Copy (Result_Definition (Parent (Subp_Id))));
2077          else
2078             return
2079               Make_Procedure_Specification (Loc,
2080                 Defining_Unit_Name       => Wrapper_Id,
2081                 Parameter_Specifications => New_Formals);
2082          end if;
2083       end;
2084    end Build_Wrapper_Spec;
2085
2086    -------------------------
2087    -- Build_Wrapper_Specs --
2088    -------------------------
2089
2090    procedure Build_Wrapper_Specs
2091      (Loc : Source_Ptr;
2092       Typ : Entity_Id;
2093       N   : in out Node_Id)
2094    is
2095       Def     : Node_Id;
2096       Rec_Typ : Entity_Id;
2097
2098    begin
2099       if Is_Protected_Type (Typ) then
2100          Def := Protected_Definition (Parent (Typ));
2101       else pragma Assert (Is_Task_Type (Typ));
2102          Def := Task_Definition (Parent (Typ));
2103       end if;
2104
2105       Rec_Typ := Corresponding_Record_Type (Typ);
2106
2107       --  Generate wrapper specs for a concurrent type which implements an
2108       --  interface and has visible entries and/or protected procedures.
2109
2110       if Present (Interfaces (Rec_Typ))
2111         and then Present (Def)
2112         and then Present (Visible_Declarations (Def))
2113       then
2114          declare
2115             Decl      : Node_Id;
2116             Wrap_Decl : Node_Id;
2117             Wrap_Spec : Node_Id;
2118
2119          begin
2120             Decl := First (Visible_Declarations (Def));
2121             while Present (Decl) loop
2122                Wrap_Spec := Empty;
2123
2124                if Nkind (Decl) = N_Entry_Declaration
2125                  and then Ekind (Defining_Identifier (Decl)) = E_Entry
2126                then
2127                   Wrap_Spec :=
2128                     Build_Wrapper_Spec (Loc,
2129                       Subp_Id => Defining_Identifier (Decl),
2130                       Obj_Typ => Rec_Typ,
2131                       Formals => Parameter_Specifications (Decl));
2132
2133                elsif Nkind (Decl) = N_Subprogram_Declaration then
2134                   Wrap_Spec :=
2135                     Build_Wrapper_Spec (Loc,
2136                       Subp_Id => Defining_Unit_Name (Specification (Decl)),
2137                       Obj_Typ => Rec_Typ,
2138                       Formals =>
2139                         Parameter_Specifications (Specification (Decl)));
2140                end if;
2141
2142                if Present (Wrap_Spec) then
2143                   Wrap_Decl :=
2144                     Make_Subprogram_Declaration (Loc,
2145                       Specification => Wrap_Spec);
2146
2147                   Insert_After (N, Wrap_Decl);
2148                   N := Wrap_Decl;
2149
2150                   Analyze (Wrap_Decl);
2151                end if;
2152
2153                Next (Decl);
2154             end loop;
2155          end;
2156       end if;
2157    end Build_Wrapper_Specs;
2158
2159    ---------------------------
2160    -- Build_Find_Body_Index --
2161    ---------------------------
2162
2163    function Build_Find_Body_Index (Typ : Entity_Id) return Node_Id is
2164       Loc   : constant Source_Ptr := Sloc (Typ);
2165       Ent   : Entity_Id;
2166       E_Typ : Entity_Id;
2167       Has_F : Boolean := False;
2168       Index : Nat;
2169       If_St : Node_Id := Empty;
2170       Lo    : Node_Id;
2171       Hi    : Node_Id;
2172       Decls : List_Id := New_List;
2173       Ret   : Node_Id;
2174       Spec  : Node_Id;
2175       Siz   : Node_Id := Empty;
2176
2177       procedure Add_If_Clause (Expr : Node_Id);
2178       --  Add test for range of current entry
2179
2180       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id;
2181       --  If a bound of an entry is given by a discriminant, retrieve the
2182       --  actual value of the discriminant from the enclosing object.
2183
2184       -------------------
2185       -- Add_If_Clause --
2186       -------------------
2187
2188       procedure Add_If_Clause (Expr : Node_Id) is
2189          Cond  : Node_Id;
2190          Stats : constant List_Id :=
2191                    New_List (
2192                      Make_Simple_Return_Statement (Loc,
2193                        Expression => Make_Integer_Literal (Loc, Index + 1)));
2194
2195       begin
2196          --  Index for current entry body
2197
2198          Index := Index + 1;
2199
2200          --  Compute total length of entry queues so far
2201
2202          if No (Siz) then
2203             Siz := Expr;
2204          else
2205             Siz :=
2206               Make_Op_Add (Loc,
2207                 Left_Opnd => Siz,
2208                 Right_Opnd => Expr);
2209          end if;
2210
2211          Cond :=
2212            Make_Op_Le (Loc,
2213              Left_Opnd => Make_Identifier (Loc, Name_uE),
2214              Right_Opnd => Siz);
2215
2216          --  Map entry queue indices in the range of the current family
2217          --  into the current index, that designates the entry body.
2218
2219          if No (If_St) then
2220             If_St :=
2221               Make_Implicit_If_Statement (Typ,
2222                 Condition => Cond,
2223                 Then_Statements => Stats,
2224                 Elsif_Parts   => New_List);
2225
2226             Ret := If_St;
2227
2228          else
2229             Append (
2230               Make_Elsif_Part (Loc,
2231                 Condition => Cond,
2232                 Then_Statements => Stats),
2233               Elsif_Parts (If_St));
2234          end if;
2235       end Add_If_Clause;
2236
2237       ------------------------------
2238       -- Convert_Discriminant_Ref --
2239       ------------------------------
2240
2241       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id is
2242          B   : Node_Id;
2243
2244       begin
2245          if Is_Entity_Name (Bound)
2246            and then Ekind (Entity (Bound)) = E_Discriminant
2247          then
2248             B :=
2249               Make_Selected_Component (Loc,
2250                Prefix =>
2251                  Unchecked_Convert_To (Corresponding_Record_Type (Typ),
2252                    Make_Explicit_Dereference (Loc,
2253                      Make_Identifier (Loc, Name_uObject))),
2254                Selector_Name => Make_Identifier (Loc, Chars (Bound)));
2255             Set_Etype (B, Etype (Entity (Bound)));
2256          else
2257             B := New_Copy_Tree (Bound);
2258          end if;
2259
2260          return B;
2261       end Convert_Discriminant_Ref;
2262
2263    --  Start of processing for Build_Find_Body_Index
2264
2265    begin
2266       Spec := Build_Find_Body_Index_Spec (Typ);
2267
2268       Ent := First_Entity (Typ);
2269       while Present (Ent) loop
2270          if Ekind (Ent) = E_Entry_Family then
2271             Has_F := True;
2272             exit;
2273          end if;
2274
2275          Next_Entity (Ent);
2276       end loop;
2277
2278       if not Has_F then
2279
2280          --  If the protected type has no entry families, there is a one-one
2281          --  correspondence between entry queue and entry body.
2282
2283          Ret :=
2284            Make_Simple_Return_Statement (Loc,
2285              Expression => Make_Identifier (Loc, Name_uE));
2286
2287       else
2288          --  Suppose entries e1, e2, ... have size l1, l2, ... we generate
2289          --  the following:
2290          --
2291          --  if E <= l1 then return 1;
2292          --  elsif E <= l1 + l2 then return 2;
2293          --  ...
2294
2295          Index := 0;
2296          Siz   := Empty;
2297          Ent   := First_Entity (Typ);
2298
2299          Add_Object_Pointer (Loc, Typ, Decls);
2300
2301          while Present (Ent) loop
2302
2303             if Ekind (Ent) = E_Entry then
2304                Add_If_Clause (Make_Integer_Literal (Loc, 1));
2305
2306             elsif Ekind (Ent) = E_Entry_Family then
2307
2308                E_Typ := Etype (Discrete_Subtype_Definition (Parent (Ent)));
2309                Hi := Convert_Discriminant_Ref (Type_High_Bound (E_Typ));
2310                Lo := Convert_Discriminant_Ref (Type_Low_Bound  (E_Typ));
2311                Add_If_Clause (Family_Size (Loc, Hi, Lo, Typ, False));
2312             end if;
2313
2314             Next_Entity (Ent);
2315          end loop;
2316
2317          if Index = 1 then
2318             Decls := New_List;
2319             Ret :=
2320               Make_Simple_Return_Statement (Loc,
2321                 Expression => Make_Integer_Literal (Loc, 1));
2322
2323          elsif Nkind (Ret) = N_If_Statement then
2324
2325             --  Ranges are in increasing order, so last one doesn't need guard
2326
2327             declare
2328                Nod : constant Node_Id := Last (Elsif_Parts (Ret));
2329             begin
2330                Remove (Nod);
2331                Set_Else_Statements (Ret, Then_Statements (Nod));
2332             end;
2333          end if;
2334       end if;
2335
2336       return
2337         Make_Subprogram_Body (Loc,
2338           Specification => Spec,
2339           Declarations  => Decls,
2340           Handled_Statement_Sequence =>
2341             Make_Handled_Sequence_Of_Statements (Loc,
2342               Statements => New_List (Ret)));
2343    end Build_Find_Body_Index;
2344
2345    --------------------------------
2346    -- Build_Find_Body_Index_Spec --
2347    --------------------------------
2348
2349    function Build_Find_Body_Index_Spec (Typ : Entity_Id) return Node_Id is
2350       Loc   : constant Source_Ptr := Sloc (Typ);
2351       Id    : constant Entity_Id :=
2352                Make_Defining_Identifier (Loc,
2353                  Chars => New_External_Name (Chars (Typ), 'F'));
2354       Parm1 : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uO);
2355       Parm2 : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uE);
2356
2357    begin
2358       return
2359         Make_Function_Specification (Loc,
2360           Defining_Unit_Name => Id,
2361           Parameter_Specifications => New_List (
2362             Make_Parameter_Specification (Loc,
2363               Defining_Identifier => Parm1,
2364               Parameter_Type =>
2365                 New_Reference_To (RTE (RE_Address), Loc)),
2366
2367             Make_Parameter_Specification (Loc,
2368               Defining_Identifier => Parm2,
2369               Parameter_Type =>
2370                 New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))),
2371           Result_Definition => New_Occurrence_Of (
2372             RTE (RE_Protected_Entry_Index), Loc));
2373    end Build_Find_Body_Index_Spec;
2374
2375    -------------------------
2376    -- Build_Master_Entity --
2377    -------------------------
2378
2379    procedure Build_Master_Entity (E : Entity_Id) is
2380       Loc  : constant Source_Ptr := Sloc (E);
2381       P    : Node_Id;
2382       Decl : Node_Id;
2383       S    : Entity_Id;
2384
2385    begin
2386       S := Scope (E);
2387
2388       --  Ada 2005 (AI-287): Do not set/get the has_master_entity reminder
2389       --  in internal scopes, unless present already.. Required for nested
2390       --  limited aggregates, where the expansion of task components may
2391       --  generate inner blocks. If the block is the rewriting of a call
2392       --  this is valid master.
2393
2394       if Ada_Version >= Ada_05 then
2395          while Is_Internal (S) loop
2396             if Nkind (Parent (S)) = N_Block_Statement
2397               and then
2398                 Nkind (Original_Node (Parent (S))) = N_Procedure_Call_Statement
2399             then
2400                exit;
2401             else
2402                S := Scope (S);
2403             end if;
2404          end loop;
2405       end if;
2406
2407       --  Nothing to do if we already built a master entity for this scope
2408       --  or if there is no task hierarchy.
2409
2410       if Has_Master_Entity (S)
2411         or else Restriction_Active (No_Task_Hierarchy)
2412       then
2413          return;
2414       end if;
2415
2416       --  Otherwise first build the master entity
2417       --    _Master : constant Master_Id := Current_Master.all;
2418       --  and insert it just before the current declaration
2419
2420       Decl :=
2421         Make_Object_Declaration (Loc,
2422           Defining_Identifier =>
2423             Make_Defining_Identifier (Loc, Name_uMaster),
2424           Constant_Present => True,
2425           Object_Definition => New_Reference_To (RTE (RE_Master_Id), Loc),
2426           Expression =>
2427             Make_Explicit_Dereference (Loc,
2428               New_Reference_To (RTE (RE_Current_Master), Loc)));
2429
2430       P := Parent (E);
2431       Insert_Before (P, Decl);
2432       Analyze (Decl);
2433
2434       --  Ada 2005 (AI-287): Set the has_master_entity reminder in the
2435       --  non-internal scope selected above.
2436
2437       if Ada_Version >= Ada_05 then
2438          Set_Has_Master_Entity (S);
2439       else
2440          Set_Has_Master_Entity (Scope (E));
2441       end if;
2442
2443       --  Now mark the containing scope as a task master
2444
2445       while Nkind (P) /= N_Compilation_Unit loop
2446          P := Parent (P);
2447
2448          --  If we fall off the top, we are at the outer level, and the
2449          --  environment task is our effective master, so nothing to mark.
2450
2451          if Nkind_In
2452               (P, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
2453          then
2454             Set_Is_Task_Master (P, True);
2455             return;
2456
2457          elsif Nkind (Parent (P)) = N_Subunit then
2458             P := Corresponding_Stub (Parent (P));
2459          end if;
2460       end loop;
2461    end Build_Master_Entity;
2462
2463    ---------------------------
2464    -- Build_Protected_Entry --
2465    ---------------------------
2466
2467    function Build_Protected_Entry
2468      (N   : Node_Id;
2469       Ent : Entity_Id;
2470       Pid : Node_Id) return Node_Id
2471    is
2472       Loc : constant Source_Ptr := Sloc (N);
2473
2474       Decls   : constant List_Id := Declarations (N);
2475       End_Lab : constant Node_Id :=
2476                   End_Label (Handled_Statement_Sequence (N));
2477       End_Loc : constant Source_Ptr :=
2478                   Sloc (Last (Statements (Handled_Statement_Sequence (N))));
2479       --  Used for the generated call to Complete_Entry_Body
2480
2481       Han_Loc : Source_Ptr;
2482       --  Used for the exception handler, inserted at end of the body
2483
2484       Op_Decls : constant List_Id := New_List;
2485       Complete : Node_Id;
2486       Edef     : Entity_Id;
2487       Espec    : Node_Id;
2488       Ohandle  : Node_Id;
2489       Op_Stats : List_Id;
2490
2491    begin
2492       --  Set the source location on the exception handler only when debugging
2493       --  the expanded code (see Make_Implicit_Exception_Handler).
2494
2495       if Debug_Generated_Code then
2496          Han_Loc := End_Loc;
2497
2498       --  Otherwise the inserted code should not be visible to the debugger
2499
2500       else
2501          Han_Loc := No_Location;
2502       end if;
2503
2504       Edef :=
2505         Make_Defining_Identifier (Loc,
2506           Chars => Chars (Protected_Body_Subprogram (Ent)));
2507       Espec :=
2508         Build_Protected_Entry_Specification (Loc, Edef, Empty);
2509
2510       --  Add the following declarations:
2511       --    type poVP is access poV;
2512       --    _object : poVP := poVP (_O);
2513       --
2514       --  where _O is the formal parameter associated with the concurrent
2515       --  object. These declarations are needed for Complete_Entry_Body.
2516
2517       Add_Object_Pointer (Loc, Pid, Op_Decls);
2518
2519       --  Add renamings for all formals, the Protection object, discriminals,
2520       --  privals and the entry index constant for use by debugger.
2521
2522       Add_Formal_Renamings (Espec, Op_Decls, Ent, Loc);
2523       Debug_Private_Data_Declarations (Decls);
2524
2525       case Corresponding_Runtime_Package (Pid) is
2526          when System_Tasking_Protected_Objects_Entries =>
2527             Complete :=
2528               New_Reference_To (RTE (RE_Complete_Entry_Body), Loc);
2529
2530          when System_Tasking_Protected_Objects_Single_Entry =>
2531             Complete :=
2532               New_Reference_To (RTE (RE_Complete_Single_Entry_Body), Loc);
2533
2534          when others =>
2535             raise Program_Error;
2536       end case;
2537
2538       Op_Stats := New_List (
2539         Make_Block_Statement (Loc,
2540           Declarations => Decls,
2541           Handled_Statement_Sequence =>
2542             Handled_Statement_Sequence (N)),
2543
2544         Make_Procedure_Call_Statement (End_Loc,
2545           Name => Complete,
2546           Parameter_Associations => New_List (
2547             Make_Attribute_Reference (End_Loc,
2548               Prefix =>
2549                 Make_Selected_Component (End_Loc,
2550                   Prefix =>
2551                     Make_Identifier (End_Loc, Name_uObject),
2552                   Selector_Name =>
2553                     Make_Identifier (End_Loc, Name_uObject)),
2554               Attribute_Name => Name_Unchecked_Access))));
2555
2556       --  When exceptions can not be propagated, we never need to call
2557       --  Exception_Complete_Entry_Body
2558
2559       if No_Exception_Handlers_Set then
2560          return
2561            Make_Subprogram_Body (Loc,
2562              Specification => Espec,
2563              Declarations => Op_Decls,
2564              Handled_Statement_Sequence =>
2565                Make_Handled_Sequence_Of_Statements (Loc,
2566                  Statements => Op_Stats,
2567                  End_Label  => End_Lab));
2568
2569       else
2570          Ohandle := Make_Others_Choice (Loc);
2571          Set_All_Others (Ohandle);
2572
2573          case Corresponding_Runtime_Package (Pid) is
2574             when System_Tasking_Protected_Objects_Entries =>
2575                Complete :=
2576                  New_Reference_To
2577                    (RTE (RE_Exceptional_Complete_Entry_Body), Loc);
2578
2579             when System_Tasking_Protected_Objects_Single_Entry =>
2580                Complete :=
2581                  New_Reference_To
2582                    (RTE (RE_Exceptional_Complete_Single_Entry_Body), Loc);
2583
2584             when others =>
2585                raise Program_Error;
2586          end case;
2587
2588          --  Create body of entry procedure. The renaming declarations are
2589          --  placed ahead of the block that contains the actual entry body.
2590
2591          return
2592            Make_Subprogram_Body (Loc,
2593              Specification => Espec,
2594              Declarations => Op_Decls,
2595              Handled_Statement_Sequence =>
2596                Make_Handled_Sequence_Of_Statements (Loc,
2597                  Statements => Op_Stats,
2598                  End_Label  => End_Lab,
2599                  Exception_Handlers => New_List (
2600                    Make_Implicit_Exception_Handler (Han_Loc,
2601                      Exception_Choices => New_List (Ohandle),
2602
2603                      Statements =>  New_List (
2604                        Make_Procedure_Call_Statement (Han_Loc,
2605                          Name => Complete,
2606                          Parameter_Associations => New_List (
2607                            Make_Attribute_Reference (Han_Loc,
2608                              Prefix =>
2609                                Make_Selected_Component (Han_Loc,
2610                                  Prefix =>
2611                                    Make_Identifier (Han_Loc, Name_uObject),
2612                                  Selector_Name =>
2613                                    Make_Identifier (Han_Loc, Name_uObject)),
2614                                Attribute_Name => Name_Unchecked_Access),
2615
2616                            Make_Function_Call (Han_Loc,
2617                              Name => New_Reference_To (
2618                                RTE (RE_Get_GNAT_Exception), Loc)))))))));
2619       end if;
2620    end Build_Protected_Entry;
2621
2622    -----------------------------------------
2623    -- Build_Protected_Entry_Specification --
2624    -----------------------------------------
2625
2626    function Build_Protected_Entry_Specification
2627      (Loc    : Source_Ptr;
2628       Def_Id : Entity_Id;
2629       Ent_Id : Entity_Id) return Node_Id
2630    is
2631       P : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uP);
2632
2633    begin
2634       Set_Debug_Info_Needed (Def_Id);
2635
2636       if Present (Ent_Id) then
2637          Append_Elmt (P, Accept_Address (Ent_Id));
2638       end if;
2639
2640       return
2641         Make_Procedure_Specification (Loc,
2642           Defining_Unit_Name => Def_Id,
2643           Parameter_Specifications => New_List (
2644             Make_Parameter_Specification (Loc,
2645               Defining_Identifier =>
2646                 Make_Defining_Identifier (Loc, Name_uO),
2647               Parameter_Type =>
2648                 New_Reference_To (RTE (RE_Address), Loc)),
2649
2650             Make_Parameter_Specification (Loc,
2651               Defining_Identifier => P,
2652               Parameter_Type =>
2653                 New_Reference_To (RTE (RE_Address), Loc)),
2654
2655             Make_Parameter_Specification (Loc,
2656               Defining_Identifier =>
2657                 Make_Defining_Identifier (Loc, Name_uE),
2658               Parameter_Type =>
2659                 New_Reference_To (RTE (RE_Protected_Entry_Index), Loc))));
2660    end Build_Protected_Entry_Specification;
2661
2662    --------------------------
2663    -- Build_Protected_Spec --
2664    --------------------------
2665
2666    function Build_Protected_Spec
2667      (N           : Node_Id;
2668       Obj_Type    : Entity_Id;
2669       Ident       : Entity_Id;
2670       Unprotected : Boolean := False) return List_Id
2671    is
2672       Loc       : constant Source_Ptr := Sloc (N);
2673       Decl      : Node_Id;
2674       Formal    : Entity_Id;
2675       New_Plist : List_Id;
2676       New_Param : Node_Id;
2677
2678    begin
2679       New_Plist := New_List;
2680
2681       Formal := First_Formal (Ident);
2682       while Present (Formal) loop
2683          New_Param :=
2684            Make_Parameter_Specification (Loc,
2685              Defining_Identifier =>
2686                Make_Defining_Identifier (Sloc (Formal), Chars (Formal)),
2687              In_Present          => In_Present (Parent (Formal)),
2688              Out_Present         => Out_Present (Parent (Formal)),
2689              Parameter_Type      => New_Reference_To (Etype (Formal), Loc));
2690
2691          if Unprotected then
2692             Set_Protected_Formal (Formal, Defining_Identifier (New_Param));
2693          end if;
2694
2695          Append (New_Param, New_Plist);
2696          Next_Formal (Formal);
2697       end loop;
2698
2699       --  If the subprogram is a procedure and the context is not an access
2700       --  to protected subprogram, the parameter is in-out. Otherwise it is
2701       --  an in parameter.
2702
2703       Decl :=
2704         Make_Parameter_Specification (Loc,
2705           Defining_Identifier =>
2706             Make_Defining_Identifier (Loc, Name_uObject),
2707           In_Present => True,
2708           Out_Present =>
2709             (Etype (Ident) = Standard_Void_Type
2710                and then not Is_RTE (Obj_Type, RE_Address)),
2711           Parameter_Type =>
2712             New_Reference_To (Obj_Type, Loc));
2713       Set_Debug_Info_Needed (Defining_Identifier (Decl));
2714       Prepend_To (New_Plist, Decl);
2715
2716       return New_Plist;
2717    end Build_Protected_Spec;
2718
2719    ---------------------------------------
2720    -- Build_Protected_Sub_Specification --
2721    ---------------------------------------
2722
2723    function Build_Protected_Sub_Specification
2724      (N        : Node_Id;
2725       Prot_Typ : Entity_Id;
2726       Mode     : Subprogram_Protection_Mode) return Node_Id
2727    is
2728       Loc       : constant Source_Ptr := Sloc (N);
2729       Decl      : Node_Id;
2730       Def_Id    : Entity_Id;
2731       New_Id    : Entity_Id;
2732       New_Plist : List_Id;
2733       New_Spec  : Node_Id;
2734
2735       Append_Chr : constant array (Subprogram_Protection_Mode) of Character :=
2736                      (Dispatching_Mode => ' ',
2737                       Protected_Mode   => 'P',
2738                       Unprotected_Mode => 'N');
2739
2740    begin
2741       if Ekind (Defining_Unit_Name (Specification (N))) =
2742            E_Subprogram_Body
2743       then
2744          Decl := Unit_Declaration_Node (Corresponding_Spec (N));
2745       else
2746          Decl := N;
2747       end if;
2748
2749       Def_Id := Defining_Unit_Name (Specification (Decl));
2750
2751       New_Plist :=
2752         Build_Protected_Spec
2753           (Decl, Corresponding_Record_Type (Prot_Typ), Def_Id,
2754            Mode = Unprotected_Mode);
2755       New_Id :=
2756         Make_Defining_Identifier (Loc,
2757           Chars => Build_Selected_Name (Prot_Typ, Def_Id, Append_Chr (Mode)));
2758
2759       --  The unprotected operation carries the user code, and debugging
2760       --  information must be generated for it, even though this spec does
2761       --  not come from source. It is also convenient to allow gdb to step
2762       --  into the protected operation, even though it only contains lock/
2763       --  unlock calls.
2764
2765       Set_Debug_Info_Needed (New_Id);
2766
2767       if Nkind (Specification (Decl)) = N_Procedure_Specification then
2768          New_Spec :=
2769            Make_Procedure_Specification (Loc,
2770              Defining_Unit_Name => New_Id,
2771              Parameter_Specifications => New_Plist);
2772
2773       --  Create a new specification for the anonymous subprogram type
2774
2775       else
2776          New_Spec :=
2777            Make_Function_Specification (Loc,
2778              Defining_Unit_Name => New_Id,
2779              Parameter_Specifications => New_Plist,
2780              Result_Definition =>
2781                Copy_Result_Type (Result_Definition (Specification (Decl))));
2782
2783          Set_Return_Present (Defining_Unit_Name (New_Spec));
2784       end if;
2785
2786       return New_Spec;
2787    end Build_Protected_Sub_Specification;
2788
2789    -------------------------------------
2790    -- Build_Protected_Subprogram_Body --
2791    -------------------------------------
2792
2793    function Build_Protected_Subprogram_Body
2794      (N         : Node_Id;
2795       Pid       : Node_Id;
2796       N_Op_Spec : Node_Id) return Node_Id
2797    is
2798       Loc          : constant Source_Ptr := Sloc (N);
2799       Op_Spec      : Node_Id;
2800       P_Op_Spec    : Node_Id;
2801       Uactuals     : List_Id;
2802       Pformal      : Node_Id;
2803       Unprot_Call  : Node_Id;
2804       Sub_Body     : Node_Id;
2805       Lock_Name    : Node_Id;
2806       Lock_Stmt    : Node_Id;
2807       Service_Name : Node_Id;
2808       R            : Node_Id;
2809       Return_Stmt  : Node_Id := Empty;    -- init to avoid gcc 3 warning
2810       Pre_Stmts    : List_Id := No_List;  -- init to avoid gcc 3 warning
2811       Stmts        : List_Id;
2812       Object_Parm  : Node_Id;
2813       Exc_Safe     : Boolean;
2814
2815       function Is_Exception_Safe (Subprogram : Node_Id) return Boolean;
2816       --  Tell whether a given subprogram cannot raise an exception
2817
2818       -----------------------
2819       -- Is_Exception_Safe --
2820       -----------------------
2821
2822       function Is_Exception_Safe (Subprogram : Node_Id) return Boolean is
2823
2824          function Has_Side_Effect (N : Node_Id) return Boolean;
2825          --  Return True whenever encountering a subprogram call or raise
2826          --  statement of any kind in the sequence of statements
2827
2828          ---------------------
2829          -- Has_Side_Effect --
2830          ---------------------
2831
2832          --  What is this doing buried two levels down in exp_ch9. It seems
2833          --  like a generally useful function, and indeed there may be code
2834          --  duplication going on here ???
2835
2836          function Has_Side_Effect (N : Node_Id) return Boolean is
2837             Stmt : Node_Id;
2838             Expr : Node_Id;
2839
2840             function Is_Call_Or_Raise (N : Node_Id) return Boolean;
2841             --  Indicate whether N is a subprogram call or a raise statement
2842
2843             ----------------------
2844             -- Is_Call_Or_Raise --
2845             ----------------------
2846
2847             function Is_Call_Or_Raise (N : Node_Id) return Boolean is
2848             begin
2849                return Nkind_In (N, N_Procedure_Call_Statement,
2850                                    N_Function_Call,
2851                                    N_Raise_Statement,
2852                                    N_Raise_Constraint_Error,
2853                                    N_Raise_Program_Error,
2854                                    N_Raise_Storage_Error);
2855             end Is_Call_Or_Raise;
2856
2857          --  Start of processing for Has_Side_Effect
2858
2859          begin
2860             Stmt := N;
2861             while Present (Stmt) loop
2862                if Is_Call_Or_Raise (Stmt) then
2863                   return True;
2864                end if;
2865
2866                --  An object declaration can also contain a function call
2867                --  or a raise statement
2868
2869                if Nkind (Stmt) = N_Object_Declaration then
2870                   Expr := Expression (Stmt);
2871
2872                   if Present (Expr) and then Is_Call_Or_Raise (Expr) then
2873                      return True;
2874                   end if;
2875                end if;
2876
2877                Next (Stmt);
2878             end loop;
2879
2880             return False;
2881          end Has_Side_Effect;
2882
2883       --  Start of processing for Is_Exception_Safe
2884
2885       begin
2886          --  If the checks handled by the back end are not disabled, we cannot
2887          --  ensure that no exception will be raised.
2888
2889          if not Access_Checks_Suppressed (Empty)
2890            or else not Discriminant_Checks_Suppressed (Empty)
2891            or else not Range_Checks_Suppressed (Empty)
2892            or else not Index_Checks_Suppressed (Empty)
2893            or else Opt.Stack_Checking_Enabled
2894          then
2895             return False;
2896          end if;
2897
2898          if Has_Side_Effect (First (Declarations (Subprogram)))
2899            or else
2900               Has_Side_Effect (
2901                 First (Statements (Handled_Statement_Sequence (Subprogram))))
2902          then
2903             return False;
2904          else
2905             return True;
2906          end if;
2907       end Is_Exception_Safe;
2908
2909    --  Start of processing for Build_Protected_Subprogram_Body
2910
2911    begin
2912       Op_Spec := Specification (N);
2913       Exc_Safe := Is_Exception_Safe (N);
2914
2915       P_Op_Spec :=
2916         Build_Protected_Sub_Specification (N, Pid, Protected_Mode);
2917
2918       --  Build a list of the formal parameters of the protected version of
2919       --  the subprogram to use as the actual parameters of the unprotected
2920       --  version.
2921
2922       Uactuals := New_List;
2923       Pformal := First (Parameter_Specifications (P_Op_Spec));
2924       while Present (Pformal) loop
2925          Append (
2926            Make_Identifier (Loc, Chars (Defining_Identifier (Pformal))),
2927            Uactuals);
2928          Next (Pformal);
2929       end loop;
2930
2931       --  Make a call to the unprotected version of the subprogram built above
2932       --  for use by the protected version built below.
2933
2934       if Nkind (Op_Spec) = N_Function_Specification then
2935          if Exc_Safe then
2936             R := Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
2937             Unprot_Call :=
2938               Make_Object_Declaration (Loc,
2939                 Defining_Identifier => R,
2940                 Constant_Present => True,
2941                 Object_Definition => New_Copy (Result_Definition (N_Op_Spec)),
2942                 Expression =>
2943                   Make_Function_Call (Loc,
2944                     Name => Make_Identifier (Loc,
2945                       Chars (Defining_Unit_Name (N_Op_Spec))),
2946                     Parameter_Associations => Uactuals));
2947             Return_Stmt := Make_Simple_Return_Statement (Loc,
2948               Expression => New_Reference_To (R, Loc));
2949
2950          else
2951             Unprot_Call := Make_Simple_Return_Statement (Loc,
2952               Expression => Make_Function_Call (Loc,
2953                 Name =>
2954                   Make_Identifier (Loc,
2955                     Chars (Defining_Unit_Name (N_Op_Spec))),
2956                 Parameter_Associations => Uactuals));
2957          end if;
2958
2959       else
2960          Unprot_Call :=
2961            Make_Procedure_Call_Statement (Loc,
2962              Name =>
2963                Make_Identifier (Loc,
2964                  Chars (Defining_Unit_Name (N_Op_Spec))),
2965              Parameter_Associations => Uactuals);
2966       end if;
2967
2968       --  Wrap call in block that will be covered by an at_end handler
2969
2970       if not Exc_Safe then
2971          Unprot_Call := Make_Block_Statement (Loc,
2972            Handled_Statement_Sequence =>
2973              Make_Handled_Sequence_Of_Statements (Loc,
2974                Statements => New_List (Unprot_Call)));
2975       end if;
2976
2977       --  Make the protected subprogram body. This locks the protected
2978       --  object and calls the unprotected version of the subprogram.
2979
2980       case Corresponding_Runtime_Package (Pid) is
2981          when System_Tasking_Protected_Objects_Entries =>
2982             Lock_Name := New_Reference_To (RTE (RE_Lock_Entries), Loc);
2983             Service_Name := New_Reference_To (RTE (RE_Service_Entries), Loc);
2984
2985          when System_Tasking_Protected_Objects_Single_Entry =>
2986             Lock_Name := New_Reference_To (RTE (RE_Lock_Entry), Loc);
2987             Service_Name := New_Reference_To (RTE (RE_Service_Entry), Loc);
2988
2989          when System_Tasking_Protected_Objects =>
2990             Lock_Name := New_Reference_To (RTE (RE_Lock), Loc);
2991             Service_Name := New_Reference_To (RTE (RE_Unlock), Loc);
2992
2993          when others =>
2994             raise Program_Error;
2995       end case;
2996
2997       Object_Parm :=
2998         Make_Attribute_Reference (Loc,
2999            Prefix =>
3000              Make_Selected_Component (Loc,
3001                Prefix =>
3002                  Make_Identifier (Loc, Name_uObject),
3003              Selector_Name =>
3004                  Make_Identifier (Loc, Name_uObject)),
3005            Attribute_Name => Name_Unchecked_Access);
3006
3007       Lock_Stmt := Make_Procedure_Call_Statement (Loc,
3008         Name => Lock_Name,
3009         Parameter_Associations => New_List (Object_Parm));
3010
3011       if Abort_Allowed then
3012          Stmts := New_List (
3013            Make_Procedure_Call_Statement (Loc,
3014              Name => New_Reference_To (RTE (RE_Abort_Defer), Loc),
3015              Parameter_Associations => Empty_List),
3016            Lock_Stmt);
3017
3018       else
3019          Stmts := New_List (Lock_Stmt);
3020       end if;
3021
3022       if not Exc_Safe then
3023          Append (Unprot_Call, Stmts);
3024       else
3025          if Nkind (Op_Spec) = N_Function_Specification then
3026             Pre_Stmts := Stmts;
3027             Stmts     := Empty_List;
3028          else
3029             Append (Unprot_Call, Stmts);
3030          end if;
3031
3032          Append (
3033            Make_Procedure_Call_Statement (Loc,
3034              Name => Service_Name,
3035              Parameter_Associations =>
3036                New_List (New_Copy_Tree (Object_Parm))),
3037            Stmts);
3038
3039          if Abort_Allowed then
3040             Append (
3041               Make_Procedure_Call_Statement (Loc,
3042                 Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc),
3043                 Parameter_Associations => Empty_List),
3044               Stmts);
3045          end if;
3046
3047          if Nkind (Op_Spec) = N_Function_Specification then
3048             Append (Return_Stmt, Stmts);
3049             Append (Make_Block_Statement (Loc,
3050               Declarations => New_List (Unprot_Call),
3051               Handled_Statement_Sequence =>
3052                 Make_Handled_Sequence_Of_Statements (Loc,
3053                   Statements => Stmts)), Pre_Stmts);
3054             Stmts := Pre_Stmts;
3055          end if;
3056       end if;
3057
3058       Sub_Body :=
3059         Make_Subprogram_Body (Loc,
3060           Declarations => Empty_List,
3061           Specification => P_Op_Spec,
3062           Handled_Statement_Sequence =>
3063             Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts));
3064
3065       if not Exc_Safe then
3066          Set_Is_Protected_Subprogram_Body (Sub_Body);
3067       end if;
3068
3069       return Sub_Body;
3070    end Build_Protected_Subprogram_Body;
3071
3072    -------------------------------------
3073    -- Build_Protected_Subprogram_Call --
3074    -------------------------------------
3075
3076    procedure Build_Protected_Subprogram_Call
3077      (N        : Node_Id;
3078       Name     : Node_Id;
3079       Rec      : Node_Id;
3080       External : Boolean := True)
3081    is
3082       Loc     : constant Source_Ptr := Sloc (N);
3083       Sub     : constant Entity_Id  := Entity (Name);
3084       New_Sub : Node_Id;
3085       Params  : List_Id;
3086
3087    begin
3088       if External then
3089          New_Sub := New_Occurrence_Of (External_Subprogram (Sub), Loc);
3090       else
3091          New_Sub :=
3092            New_Occurrence_Of (Protected_Body_Subprogram (Sub), Loc);
3093       end if;
3094
3095       if Present (Parameter_Associations (N)) then
3096          Params := New_Copy_List_Tree (Parameter_Associations (N));
3097       else
3098          Params := New_List;
3099       end if;
3100
3101       Prepend (Rec, Params);
3102
3103       if Ekind (Sub) = E_Procedure then
3104          Rewrite (N,
3105            Make_Procedure_Call_Statement (Loc,
3106              Name => New_Sub,
3107              Parameter_Associations => Params));
3108
3109       else
3110          pragma Assert (Ekind (Sub) = E_Function);
3111          Rewrite (N,
3112            Make_Function_Call (Loc,
3113              Name => New_Sub,
3114              Parameter_Associations => Params));
3115       end if;
3116
3117       if External
3118         and then Nkind (Rec) = N_Unchecked_Type_Conversion
3119         and then Is_Entity_Name (Expression (Rec))
3120         and then Is_Shared_Passive (Entity (Expression (Rec)))
3121       then
3122          Add_Shared_Var_Lock_Procs (N);
3123       end if;
3124    end Build_Protected_Subprogram_Call;
3125
3126    -------------------------
3127    -- Build_Selected_Name --
3128    -------------------------
3129
3130    function Build_Selected_Name
3131      (Prefix      : Entity_Id;
3132       Selector    : Entity_Id;
3133       Append_Char : Character := ' ') return Name_Id
3134    is
3135       Select_Buffer : String (1 .. Hostparm.Max_Name_Length);
3136       Select_Len    : Natural;
3137
3138    begin
3139       Get_Name_String (Chars (Selector));
3140       Select_Len := Name_Len;
3141       Select_Buffer (1 .. Select_Len) := Name_Buffer (1 .. Name_Len);
3142       Get_Name_String (Chars (Prefix));
3143
3144       --  If scope is anonymous type, discard suffix to recover name of
3145       --  single protected object. Otherwise use protected type name.
3146
3147       if Name_Buffer (Name_Len) = 'T' then
3148          Name_Len := Name_Len - 1;
3149       end if;
3150
3151       Name_Buffer (Name_Len + 1) := '_';
3152       Name_Buffer (Name_Len + 2) := '_';
3153
3154       Name_Len := Name_Len + 2;
3155       for J in 1 .. Select_Len loop
3156          Name_Len := Name_Len + 1;
3157          Name_Buffer (Name_Len) := Select_Buffer (J);
3158       end loop;
3159
3160       --  Now add the Append_Char if specified. The encoding to follow
3161       --  depends on the type of entity. If Append_Char is either 'N' or 'P',
3162       --  then the entity is associated to a protected type subprogram.
3163       --  Otherwise, it is a protected type entry. For each case, the
3164       --  encoding to follow for the suffix is documented in exp_dbug.ads.
3165
3166       --  It would be better to encapsulate this as a routine in Exp_Dbug ???
3167
3168       if Append_Char /= ' ' then
3169          if Append_Char = 'P' or Append_Char = 'N' then
3170             Name_Len := Name_Len + 1;
3171             Name_Buffer (Name_Len) := Append_Char;
3172             return Name_Find;
3173          else
3174             Name_Buffer (Name_Len + 1) := '_';
3175             Name_Buffer (Name_Len + 2) := Append_Char;
3176             Name_Len := Name_Len + 2;
3177             return New_External_Name (Name_Find, ' ', -1);
3178          end if;
3179       else
3180          return Name_Find;
3181       end if;
3182    end Build_Selected_Name;
3183
3184    -----------------------------
3185    -- Build_Simple_Entry_Call --
3186    -----------------------------
3187
3188    --  A task entry call is converted to a call to Call_Simple
3189
3190    --    declare
3191    --       P : parms := (parm, parm, parm);
3192    --    begin
3193    --       Call_Simple (acceptor-task, entry-index, P'Address);
3194    --       parm := P.param;
3195    --       parm := P.param;
3196    --       ...
3197    --    end;
3198
3199    --  Here Pnn is an aggregate of the type constructed for the entry to hold
3200    --  the parameters, and the constructed aggregate value contains either the
3201    --  parameters or, in the case of non-elementary types, references to these
3202    --  parameters. Then the address of this aggregate is passed to the runtime
3203    --  routine, along with the task id value and the task entry index value.
3204    --  Pnn is only required if parameters are present.
3205
3206    --  The assignments after the call are present only in the case of in-out
3207    --  or out parameters for elementary types, and are used to assign back the
3208    --  resulting values of such parameters.
3209
3210    --  Note: the reason that we insert a block here is that in the context
3211    --  of selects, conditional entry calls etc. the entry call statement
3212    --  appears on its own, not as an element of a list.
3213
3214    --  A protected entry call is converted to a Protected_Entry_Call:
3215
3216    --  declare
3217    --     P   : E1_Params := (param, param, param);
3218    --     Pnn : Boolean;
3219    --     Bnn : Communications_Block;
3220
3221    --  declare
3222    --     P   : E1_Params := (param, param, param);
3223    --     Bnn : Communications_Block;
3224
3225    --  begin
3226    --     Protected_Entry_Call (
3227    --       Object => po._object'Access,
3228    --       E => <entry index>;
3229    --       Uninterpreted_Data => P'Address;
3230    --       Mode => Simple_Call;
3231    --       Block => Bnn);
3232    --     parm := P.param;
3233    --     parm := P.param;
3234    --       ...
3235    --  end;
3236
3237    procedure Build_Simple_Entry_Call
3238      (N       : Node_Id;
3239       Concval : Node_Id;
3240       Ename   : Node_Id;
3241       Index   : Node_Id)
3242    is
3243    begin
3244       Expand_Call (N);
3245
3246       --  If call has been inlined, nothing left to do
3247
3248       if Nkind (N) = N_Block_Statement then
3249          return;
3250       end if;
3251
3252       --  Convert entry call to Call_Simple call
3253
3254       declare
3255          Loc       : constant Source_Ptr := Sloc (N);
3256          Parms     : constant List_Id    := Parameter_Associations (N);
3257          Stats     : constant List_Id    := New_List;
3258          Actual    : Node_Id;
3259          Call      : Node_Id;
3260          Comm_Name : Entity_Id;
3261          Conctyp   : Node_Id;
3262          Decls     : List_Id;
3263          Ent       : Entity_Id;
3264          Ent_Acc   : Entity_Id;
3265          Formal    : Node_Id;
3266          Iface_Tag : Entity_Id;
3267          Iface_Typ : Entity_Id;
3268          N_Node    : Node_Id;
3269          N_Var     : Node_Id;
3270          P         : Entity_Id;
3271          Parm1     : Node_Id;
3272          Parm2     : Node_Id;
3273          Parm3     : Node_Id;
3274          Pdecl     : Node_Id;
3275          Plist     : List_Id;
3276          X         : Entity_Id;
3277          Xdecl     : Node_Id;
3278
3279       begin
3280          --  Simple entry and entry family cases merge here
3281
3282          Ent     := Entity (Ename);
3283          Ent_Acc := Entry_Parameters_Type (Ent);
3284          Conctyp := Etype (Concval);
3285
3286          --  If prefix is an access type, dereference to obtain the task type
3287
3288          if Is_Access_Type (Conctyp) then
3289             Conctyp := Designated_Type (Conctyp);
3290          end if;
3291
3292          --  Special case for protected subprogram calls
3293
3294          if Is_Protected_Type (Conctyp)
3295            and then Is_Subprogram (Entity (Ename))
3296          then
3297             if not Is_Eliminated (Entity (Ename)) then
3298                Build_Protected_Subprogram_Call
3299                  (N, Ename, Convert_Concurrent (Concval, Conctyp));
3300                Analyze (N);
3301             end if;
3302
3303             return;
3304          end if;
3305
3306          --  First parameter is the Task_Id value from the task value or the
3307          --  Object from the protected object value, obtained by selecting
3308          --  the _Task_Id or _Object from the result of doing an unchecked
3309          --  conversion to convert the value to the corresponding record type.
3310
3311          if Nkind (Concval) = N_Function_Call
3312            and then Is_Task_Type (Conctyp)
3313            and then Ada_Version >= Ada_05
3314          then
3315             declare
3316                Obj : constant Entity_Id :=
3317                   Make_Defining_Identifier (Loc, New_Internal_Name ('F'));
3318                Decl : Node_Id;
3319
3320             begin
3321                Decl :=
3322                  Make_Object_Declaration (Loc,
3323                    Defining_Identifier => Obj,
3324                    Object_Definition   => New_Occurrence_Of (Conctyp, Loc),
3325                    Expression          => Relocate_Node (Concval));
3326                Set_Etype (Obj, Conctyp);
3327                Decls := New_List (Decl);
3328                Rewrite (Concval, New_Occurrence_Of (Obj, Loc));
3329             end;
3330
3331          else
3332             Decls := New_List;
3333          end if;
3334
3335          Parm1 := Concurrent_Ref (Concval);
3336
3337          --  Second parameter is the entry index, computed by the routine
3338          --  provided for this purpose. The value of this expression is
3339          --  assigned to an intermediate variable to assure that any entry
3340          --  family index expressions are evaluated before the entry
3341          --  parameters.
3342
3343          if Abort_Allowed
3344            or else Restriction_Active (No_Entry_Queue) = False
3345            or else not Is_Protected_Type (Conctyp)
3346            or else Number_Entries (Conctyp) > 1
3347            or else (Has_Attach_Handler (Conctyp)
3348                      and then not Restricted_Profile)
3349          then
3350             X := Make_Defining_Identifier (Loc, Name_uX);
3351
3352             Xdecl :=
3353               Make_Object_Declaration (Loc,
3354                 Defining_Identifier => X,
3355                 Object_Definition =>
3356                   New_Reference_To (RTE (RE_Task_Entry_Index), Loc),
3357                 Expression => Actual_Index_Expression (
3358                   Loc, Entity (Ename), Index, Concval));
3359
3360             Append_To (Decls, Xdecl);
3361             Parm2 := New_Reference_To (X, Loc);
3362
3363          else
3364             Xdecl := Empty;
3365             Parm2 := Empty;
3366          end if;
3367
3368          --  The third parameter is the packaged parameters. If there are
3369          --  none, then it is just the null address, since nothing is passed.
3370
3371          if No (Parms) then
3372             Parm3 := New_Reference_To (RTE (RE_Null_Address), Loc);
3373             P := Empty;
3374
3375          --  Case of parameters present, where third argument is the address
3376          --  of a packaged record containing the required parameter values.
3377
3378          else
3379             --  First build a list of parameter values, which are references to
3380             --  objects of the parameter types.
3381
3382             Plist := New_List;
3383
3384             Actual := First_Actual (N);
3385             Formal := First_Formal (Ent);
3386
3387             while Present (Actual) loop
3388
3389                --  If it is a by_copy_type, copy it to a new variable. The
3390                --  packaged record has a field that points to this variable.
3391
3392                if Is_By_Copy_Type (Etype (Actual)) then
3393                   N_Node :=
3394                     Make_Object_Declaration (Loc,
3395                       Defining_Identifier =>
3396                         Make_Defining_Identifier (Loc,
3397                           Chars => New_Internal_Name ('J')),
3398                       Aliased_Present => True,
3399                       Object_Definition =>
3400                         New_Reference_To (Etype (Formal), Loc));
3401
3402                   --  Mark the object as not needing initialization since the
3403                   --  initialization is performed separately, avoiding errors
3404                   --  on cases such as formals of null-excluding access types.
3405
3406                   Set_No_Initialization (N_Node);
3407
3408                   --  We must make an assignment statement separate for the
3409                   --  case of limited type. We cannot assign it unless the
3410                   --  Assignment_OK flag is set first. An out formal of an
3411                   --  access type must also be initialized from the actual,
3412                   --  as stated in RM 6.4.1 (13).
3413
3414                   if Ekind (Formal) /= E_Out_Parameter
3415                     or else Is_Access_Type (Etype (Formal))
3416                   then
3417                      N_Var :=
3418                        New_Reference_To (Defining_Identifier (N_Node), Loc);
3419                      Set_Assignment_OK (N_Var);
3420                      Append_To (Stats,
3421                        Make_Assignment_Statement (Loc,
3422                          Name => N_Var,
3423                          Expression => Relocate_Node (Actual)));
3424                   end if;
3425
3426                   Append (N_Node, Decls);
3427
3428                   Append_To (Plist,
3429                     Make_Attribute_Reference (Loc,
3430                       Attribute_Name => Name_Unchecked_Access,
3431                     Prefix =>
3432                       New_Reference_To (Defining_Identifier (N_Node), Loc)));
3433                else
3434                   --  Interface class-wide formal
3435
3436                   if Ada_Version >= Ada_05
3437                     and then Ekind (Etype (Formal)) = E_Class_Wide_Type
3438                     and then Is_Interface (Etype (Formal))
3439                   then
3440                      Iface_Typ := Etype (Etype (Formal));
3441
3442                      --  Generate:
3443                      --    formal_iface_type! (actual.iface_tag)'reference
3444
3445                      Iface_Tag :=
3446                        Find_Interface_Tag (Etype (Actual), Iface_Typ);
3447                      pragma Assert (Present (Iface_Tag));
3448
3449                      Append_To (Plist,
3450                        Make_Reference (Loc,
3451                          Unchecked_Convert_To (Iface_Typ,
3452                            Make_Selected_Component (Loc,
3453                              Prefix =>
3454                                Relocate_Node (Actual),
3455                              Selector_Name =>
3456                                New_Reference_To (Iface_Tag, Loc)))));
3457                   else
3458                      --  Generate:
3459                      --    actual'reference
3460
3461                      Append_To (Plist,
3462                        Make_Reference (Loc, Relocate_Node (Actual)));
3463                   end if;
3464                end if;
3465
3466                Next_Actual (Actual);
3467                Next_Formal_With_Extras (Formal);
3468             end loop;
3469
3470             --  Now build the declaration of parameters initialized with the
3471             --  aggregate containing this constructed parameter list.
3472
3473             P := Make_Defining_Identifier (Loc, Name_uP);
3474
3475             Pdecl :=
3476               Make_Object_Declaration (Loc,
3477                 Defining_Identifier => P,
3478                 Object_Definition =>
3479                   New_Reference_To (Designated_Type (Ent_Acc), Loc),
3480                 Expression =>
3481                   Make_Aggregate (Loc, Expressions => Plist));
3482
3483             Parm3 :=
3484               Make_Attribute_Reference (Loc,
3485                 Prefix => New_Reference_To (P, Loc),
3486                 Attribute_Name => Name_Address);
3487
3488             Append (Pdecl, Decls);
3489          end if;
3490
3491          --  Now we can create the call, case of protected type
3492
3493          if Is_Protected_Type (Conctyp) then
3494             case Corresponding_Runtime_Package (Conctyp) is
3495                when System_Tasking_Protected_Objects_Entries =>
3496
3497                   --  Change the type of the index declaration
3498
3499                   Set_Object_Definition (Xdecl,
3500                     New_Reference_To (RTE (RE_Protected_Entry_Index), Loc));
3501
3502                   --  Some additional declarations for protected entry calls
3503
3504                   if No (Decls) then
3505                      Decls := New_List;
3506                   end if;
3507
3508                   --  Bnn : Communications_Block;
3509
3510                   Comm_Name :=
3511                     Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
3512
3513                   Append_To (Decls,
3514                     Make_Object_Declaration (Loc,
3515                       Defining_Identifier => Comm_Name,
3516                       Object_Definition =>
3517                         New_Reference_To (RTE (RE_Communication_Block), Loc)));
3518
3519                   --  Some additional statements for protected entry calls
3520
3521                   --     Protected_Entry_Call (
3522                   --       Object => po._object'Access,
3523                   --       E => <entry index>;
3524                   --       Uninterpreted_Data => P'Address;
3525                   --       Mode => Simple_Call;
3526                   --       Block => Bnn);
3527
3528                   Call :=
3529                     Make_Procedure_Call_Statement (Loc,
3530                       Name =>
3531                         New_Reference_To (RTE (RE_Protected_Entry_Call), Loc),
3532
3533                       Parameter_Associations => New_List (
3534                         Make_Attribute_Reference (Loc,
3535                           Attribute_Name => Name_Unchecked_Access,
3536                           Prefix         => Parm1),
3537                         Parm2,
3538                         Parm3,
3539                         New_Reference_To (RTE (RE_Simple_Call), Loc),
3540                         New_Occurrence_Of (Comm_Name, Loc)));
3541
3542                when System_Tasking_Protected_Objects_Single_Entry =>
3543                   --     Protected_Single_Entry_Call (
3544                   --       Object => po._object'Access,
3545                   --       Uninterpreted_Data => P'Address;
3546                   --       Mode => Simple_Call);
3547
3548                   Call :=
3549                     Make_Procedure_Call_Statement (Loc,
3550                       Name => New_Reference_To (
3551                         RTE (RE_Protected_Single_Entry_Call), Loc),
3552
3553                       Parameter_Associations => New_List (
3554                         Make_Attribute_Reference (Loc,
3555                           Attribute_Name => Name_Unchecked_Access,
3556                           Prefix         => Parm1),
3557                         Parm3,
3558                         New_Reference_To (RTE (RE_Simple_Call), Loc)));
3559
3560                when others =>
3561                   raise Program_Error;
3562             end case;
3563
3564          --  Case of task type
3565
3566          else
3567             Call :=
3568               Make_Procedure_Call_Statement (Loc,
3569                 Name => New_Reference_To (RTE (RE_Call_Simple), Loc),
3570                 Parameter_Associations => New_List (Parm1, Parm2, Parm3));
3571
3572          end if;
3573
3574          Append_To (Stats, Call);
3575
3576          --  If there are out or in/out parameters by copy add assignment
3577          --  statements for the result values.
3578
3579          if Present (Parms) then
3580             Actual := First_Actual (N);
3581             Formal := First_Formal (Ent);
3582
3583             Set_Assignment_OK (Actual);
3584             while Present (Actual) loop
3585                if Is_By_Copy_Type (Etype (Actual))
3586                  and then Ekind (Formal) /= E_In_Parameter
3587                then
3588                   N_Node :=
3589                     Make_Assignment_Statement (Loc,
3590                       Name => New_Copy (Actual),
3591                       Expression =>
3592                         Make_Explicit_Dereference (Loc,
3593                           Make_Selected_Component (Loc,
3594                             Prefix => New_Reference_To (P, Loc),
3595                             Selector_Name =>
3596                               Make_Identifier (Loc, Chars (Formal)))));
3597
3598                   --  In all cases (including limited private types) we want
3599                   --  the assignment to be valid.
3600
3601                   Set_Assignment_OK (Name (N_Node));
3602
3603                   --  If the call is the triggering alternative in an
3604                   --  asynchronous select, or the entry_call alternative of a
3605                   --  conditional entry call, the assignments for in-out
3606                   --  parameters are incorporated into the statement list that
3607                   --  follows, so that there are executed only if the entry
3608                   --  call succeeds.
3609
3610                   if (Nkind (Parent (N)) = N_Triggering_Alternative
3611                        and then N = Triggering_Statement (Parent (N)))
3612                     or else
3613                      (Nkind (Parent (N)) = N_Entry_Call_Alternative
3614                        and then N = Entry_Call_Statement (Parent (N)))
3615                   then
3616                      if No (Statements (Parent (N))) then
3617                         Set_Statements (Parent (N), New_List);
3618                      end if;
3619
3620                      Prepend (N_Node, Statements (Parent (N)));
3621
3622                   else
3623                      Insert_After (Call, N_Node);
3624                   end if;
3625                end if;
3626
3627                Next_Actual (Actual);
3628                Next_Formal_With_Extras (Formal);
3629             end loop;
3630          end if;
3631
3632          --  Finally, create block and analyze it
3633
3634          Rewrite (N,
3635            Make_Block_Statement (Loc,
3636              Declarations => Decls,
3637              Handled_Statement_Sequence =>
3638                Make_Handled_Sequence_Of_Statements (Loc,
3639                  Statements => Stats)));
3640
3641          Analyze (N);
3642       end;
3643    end Build_Simple_Entry_Call;
3644
3645    --------------------------------
3646    -- Build_Task_Activation_Call --
3647    --------------------------------
3648
3649    procedure Build_Task_Activation_Call (N : Node_Id) is
3650       Loc   : constant Source_Ptr := Sloc (N);
3651       Chain : Entity_Id;
3652       Call  : Node_Id;
3653       Name  : Node_Id;
3654       P     : Node_Id;
3655
3656    begin
3657       --  Get the activation chain entity. Except in the case of a package
3658       --  body, this is in the node that was passed. For a package body, we
3659       --  have to find the corresponding package declaration node.
3660
3661       if Nkind (N) = N_Package_Body then
3662          P := Corresponding_Spec (N);
3663          loop
3664             P := Parent (P);
3665             exit when Nkind (P) = N_Package_Declaration;
3666          end loop;
3667
3668          Chain := Activation_Chain_Entity (P);
3669
3670       else
3671          Chain := Activation_Chain_Entity (N);
3672       end if;
3673
3674       if Present (Chain) then
3675          if Restricted_Profile then
3676             Name := New_Reference_To (RTE (RE_Activate_Restricted_Tasks), Loc);
3677          else
3678             Name := New_Reference_To (RTE (RE_Activate_Tasks), Loc);
3679          end if;
3680
3681          Call :=
3682            Make_Procedure_Call_Statement (Loc,
3683              Name => Name,
3684              Parameter_Associations =>
3685                New_List (Make_Attribute_Reference (Loc,
3686                  Prefix => New_Occurrence_Of (Chain, Loc),
3687                  Attribute_Name => Name_Unchecked_Access)));
3688
3689          if Nkind (N) = N_Package_Declaration then
3690             if Present (Corresponding_Body (N)) then
3691                null;
3692
3693             elsif Present (Private_Declarations (Specification (N))) then
3694                Append (Call, Private_Declarations (Specification (N)));
3695
3696             else
3697                Append (Call, Visible_Declarations (Specification (N)));
3698             end if;
3699
3700          else
3701             if Present (Handled_Statement_Sequence (N)) then
3702
3703                --  The call goes at the start of the statement sequence
3704                --  after the start of exception range label if one is present.
3705
3706                declare
3707                   Stm : Node_Id;
3708
3709                begin
3710                   Stm := First (Statements (Handled_Statement_Sequence (N)));
3711
3712                   --  A special case, skip exception range label if one is
3713                   --  present (from front end zcx processing).
3714
3715                   if Nkind (Stm) = N_Label and then Exception_Junk (Stm) then
3716                      Next (Stm);
3717                   end if;
3718
3719                   --  Another special case, if the first statement is a block
3720                   --  from optimization of a local raise to a goto, then the
3721                   --  call goes inside this block.
3722
3723                   if Nkind (Stm) = N_Block_Statement
3724                     and then Exception_Junk (Stm)
3725                   then
3726                      Stm :=
3727                        First (Statements (Handled_Statement_Sequence (Stm)));
3728                   end if;
3729
3730                   --  Insertion point is after any exception label pushes,
3731                   --  since we want it covered by any local handlers.
3732
3733                   while Nkind (Stm) in N_Push_xxx_Label loop
3734                      Next (Stm);
3735                   end loop;
3736
3737                   --  Now we have the proper insertion point
3738
3739                   Insert_Before (Stm, Call);
3740                end;
3741
3742             else
3743                Set_Handled_Statement_Sequence (N,
3744                   Make_Handled_Sequence_Of_Statements (Loc,
3745                      Statements => New_List (Call)));
3746             end if;
3747          end if;
3748
3749          Analyze (Call);
3750          Check_Task_Activation (N);
3751       end if;
3752    end Build_Task_Activation_Call;
3753
3754    -------------------------------
3755    -- Build_Task_Allocate_Block --
3756    -------------------------------
3757
3758    procedure Build_Task_Allocate_Block
3759      (Actions : List_Id;
3760       N       : Node_Id;
3761       Args    : List_Id)
3762    is
3763       T      : constant Entity_Id  := Entity (Expression (N));
3764       Init   : constant Entity_Id  := Base_Init_Proc (T);
3765       Loc    : constant Source_Ptr := Sloc (N);
3766       Chain  : constant Entity_Id  :=
3767                  Make_Defining_Identifier (Loc, Name_uChain);
3768
3769       Blkent : Entity_Id;
3770       Block  : Node_Id;
3771
3772    begin
3773       Blkent := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
3774
3775       Block :=
3776         Make_Block_Statement (Loc,
3777           Identifier => New_Reference_To (Blkent, Loc),
3778           Declarations => New_List (
3779
3780             --  _Chain  : Activation_Chain;
3781
3782             Make_Object_Declaration (Loc,
3783               Defining_Identifier => Chain,
3784               Aliased_Present => True,
3785               Object_Definition   =>
3786                 New_Reference_To (RTE (RE_Activation_Chain), Loc))),
3787
3788           Handled_Statement_Sequence =>
3789             Make_Handled_Sequence_Of_Statements (Loc,
3790
3791               Statements => New_List (
3792
3793                --  Init (Args);
3794
3795                 Make_Procedure_Call_Statement (Loc,
3796                   Name => New_Reference_To (Init, Loc),
3797                   Parameter_Associations => Args),
3798
3799                --  Activate_Tasks (_Chain);
3800
3801                 Make_Procedure_Call_Statement (Loc,
3802                   Name => New_Reference_To (RTE (RE_Activate_Tasks), Loc),
3803                   Parameter_Associations => New_List (
3804                     Make_Attribute_Reference (Loc,
3805                       Prefix => New_Reference_To (Chain, Loc),
3806                       Attribute_Name => Name_Unchecked_Access))))),
3807
3808           Has_Created_Identifier => True,
3809           Is_Task_Allocation_Block => True);
3810
3811       Append_To (Actions,
3812         Make_Implicit_Label_Declaration (Loc,
3813           Defining_Identifier => Blkent,
3814           Label_Construct     => Block));
3815
3816       Append_To (Actions, Block);
3817
3818       Set_Activation_Chain_Entity (Block, Chain);
3819    end Build_Task_Allocate_Block;
3820
3821    -----------------------------------------------
3822    -- Build_Task_Allocate_Block_With_Init_Stmts --
3823    -----------------------------------------------
3824
3825    procedure Build_Task_Allocate_Block_With_Init_Stmts
3826      (Actions    : List_Id;
3827       N          : Node_Id;
3828       Init_Stmts : List_Id)
3829    is
3830       Loc    : constant Source_Ptr := Sloc (N);
3831       Chain  : constant Entity_Id  :=
3832                  Make_Defining_Identifier (Loc, Name_uChain);
3833       Blkent : Entity_Id;
3834       Block  : Node_Id;
3835
3836    begin
3837       Blkent := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
3838
3839       Append_To (Init_Stmts,
3840         Make_Procedure_Call_Statement (Loc,
3841           Name => New_Reference_To (RTE (RE_Activate_Tasks), Loc),
3842           Parameter_Associations => New_List (
3843             Make_Attribute_Reference (Loc,
3844               Prefix => New_Reference_To (Chain, Loc),
3845               Attribute_Name => Name_Unchecked_Access))));
3846
3847       Block :=
3848         Make_Block_Statement (Loc,
3849           Identifier => New_Reference_To (Blkent, Loc),
3850           Declarations => New_List (
3851
3852             --  _Chain  : Activation_Chain;
3853
3854             Make_Object_Declaration (Loc,
3855               Defining_Identifier => Chain,
3856               Aliased_Present => True,
3857               Object_Definition   =>
3858                 New_Reference_To (RTE (RE_Activation_Chain), Loc))),
3859
3860           Handled_Statement_Sequence =>
3861             Make_Handled_Sequence_Of_Statements (Loc, Init_Stmts),
3862
3863           Has_Created_Identifier => True,
3864           Is_Task_Allocation_Block => True);
3865
3866       Append_To (Actions,
3867         Make_Implicit_Label_Declaration (Loc,
3868           Defining_Identifier => Blkent,
3869           Label_Construct     => Block));
3870
3871       Append_To (Actions, Block);
3872
3873       Set_Activation_Chain_Entity (Block, Chain);
3874    end Build_Task_Allocate_Block_With_Init_Stmts;
3875
3876    -----------------------------------
3877    -- Build_Task_Proc_Specification --
3878    -----------------------------------
3879
3880    function Build_Task_Proc_Specification (T : Entity_Id) return Node_Id is
3881       Loc     : constant Source_Ptr := Sloc (T);
3882       Spec_Id : Entity_Id;
3883
3884    begin
3885       Spec_Id :=
3886         Make_Defining_Identifier (Loc,
3887           Chars => New_External_Name (Chars (T), 'B'));
3888       Set_Is_Internal (Spec_Id);
3889
3890       --  Associate the procedure with the task, if this is the declaration
3891       --  (and not the body) of the procedure.
3892
3893       if No (Task_Body_Procedure (T)) then
3894          Set_Task_Body_Procedure (T, Spec_Id);
3895       end if;
3896
3897       return
3898         Make_Procedure_Specification (Loc,
3899           Defining_Unit_Name       => Spec_Id,
3900           Parameter_Specifications => New_List (
3901             Make_Parameter_Specification (Loc,
3902               Defining_Identifier =>
3903                 Make_Defining_Identifier (Loc, Name_uTask),
3904               Parameter_Type      =>
3905                 Make_Access_Definition (Loc,
3906                   Subtype_Mark =>
3907                     New_Reference_To (Corresponding_Record_Type (T), Loc)))));
3908    end Build_Task_Proc_Specification;
3909
3910    ---------------------------------------
3911    -- Build_Unprotected_Subprogram_Body --
3912    ---------------------------------------
3913
3914    function Build_Unprotected_Subprogram_Body
3915      (N   : Node_Id;
3916       Pid : Node_Id) return Node_Id
3917    is
3918       Decls : constant List_Id := Declarations (N);
3919
3920    begin
3921       --  Add renamings for the Protection object, discriminals, privals and
3922       --  the entry index constant for use by debugger.
3923
3924       Debug_Private_Data_Declarations (Decls);
3925
3926       --  Make an unprotected version of the subprogram for use within the same
3927       --  object, with a new name and an additional parameter representing the
3928       --  object.
3929
3930       return
3931         Make_Subprogram_Body (Sloc (N),
3932           Specification              =>
3933             Build_Protected_Sub_Specification (N, Pid, Unprotected_Mode),
3934           Declarations               => Decls,
3935           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
3936    end Build_Unprotected_Subprogram_Body;
3937
3938    ----------------------------
3939    -- Collect_Entry_Families --
3940    ----------------------------
3941
3942    procedure Collect_Entry_Families
3943      (Loc          : Source_Ptr;
3944       Cdecls       : List_Id;
3945       Current_Node : in out Node_Id;
3946       Conctyp      : Entity_Id)
3947    is
3948       Efam      : Entity_Id;
3949       Efam_Decl : Node_Id;
3950       Efam_Type : Entity_Id;
3951
3952    begin
3953       Efam := First_Entity (Conctyp);
3954       while Present (Efam) loop
3955          if Ekind (Efam) = E_Entry_Family then
3956             Efam_Type :=
3957               Make_Defining_Identifier (Loc,
3958                 Chars => New_Internal_Name ('F'));
3959
3960             declare
3961                Bas : Entity_Id :=
3962                        Base_Type
3963                         (Etype (Discrete_Subtype_Definition (Parent (Efam))));
3964
3965                Bas_Decl : Node_Id := Empty;
3966                Lo, Hi   : Node_Id;
3967
3968             begin
3969                Get_Index_Bounds
3970                  (Discrete_Subtype_Definition (Parent (Efam)), Lo, Hi);
3971
3972                if Is_Potentially_Large_Family (Bas, Conctyp, Lo, Hi) then
3973                   Bas :=
3974                     Make_Defining_Identifier (Loc,
3975                       Chars => New_Internal_Name ('B'));
3976
3977                   Bas_Decl :=
3978                     Make_Subtype_Declaration (Loc,
3979                        Defining_Identifier => Bas,
3980                        Subtype_Indication  =>
3981                          Make_Subtype_Indication (Loc,
3982                            Subtype_Mark =>
3983                              New_Occurrence_Of (Standard_Integer, Loc),
3984                            Constraint   =>
3985                              Make_Range_Constraint (Loc,
3986                                Range_Expression => Make_Range (Loc,
3987                                  Make_Integer_Literal
3988                                    (Loc, -Entry_Family_Bound),
3989                                  Make_Integer_Literal
3990                                    (Loc, Entry_Family_Bound - 1)))));
3991
3992                   Insert_After (Current_Node, Bas_Decl);
3993                   Current_Node := Bas_Decl;
3994                   Analyze (Bas_Decl);
3995                end if;
3996
3997                Efam_Decl :=
3998                  Make_Full_Type_Declaration (Loc,
3999                    Defining_Identifier => Efam_Type,
4000                    Type_Definition =>
4001                      Make_Unconstrained_Array_Definition (Loc,
4002                        Subtype_Marks =>
4003                          (New_List (New_Occurrence_Of (Bas, Loc))),
4004
4005                     Component_Definition =>
4006                       Make_Component_Definition (Loc,
4007                         Aliased_Present    => False,
4008                         Subtype_Indication =>
4009                           New_Reference_To (Standard_Character, Loc))));
4010             end;
4011
4012             Insert_After (Current_Node, Efam_Decl);
4013             Current_Node := Efam_Decl;
4014             Analyze (Efam_Decl);
4015
4016             Append_To (Cdecls,
4017               Make_Component_Declaration (Loc,
4018                 Defining_Identifier =>
4019                   Make_Defining_Identifier (Loc, Chars (Efam)),
4020
4021                 Component_Definition =>
4022                   Make_Component_Definition (Loc,
4023                     Aliased_Present    => False,
4024                     Subtype_Indication =>
4025                       Make_Subtype_Indication (Loc,
4026                         Subtype_Mark =>
4027                           New_Occurrence_Of (Efam_Type, Loc),
4028
4029                         Constraint  =>
4030                           Make_Index_Or_Discriminant_Constraint (Loc,
4031                             Constraints => New_List (
4032                               New_Occurrence_Of
4033                                 (Etype (Discrete_Subtype_Definition
4034                                   (Parent (Efam))), Loc)))))));
4035
4036          end if;
4037
4038          Next_Entity (Efam);
4039       end loop;
4040    end Collect_Entry_Families;
4041
4042    -----------------------
4043    -- Concurrent_Object --
4044    -----------------------
4045
4046    function Concurrent_Object
4047      (Spec_Id  : Entity_Id;
4048       Conc_Typ : Entity_Id) return Entity_Id
4049    is
4050    begin
4051       --  Parameter _O or _object
4052
4053       if Is_Protected_Type (Conc_Typ) then
4054          return First_Formal (Protected_Body_Subprogram (Spec_Id));
4055
4056       --  Parameter _task
4057
4058       else
4059          pragma Assert (Is_Task_Type (Conc_Typ));
4060          return First_Formal (Task_Body_Procedure (Conc_Typ));
4061       end if;
4062    end Concurrent_Object;
4063
4064    ----------------------
4065    -- Copy_Result_Type --
4066    ----------------------
4067
4068    function Copy_Result_Type (Res : Node_Id) return Node_Id is
4069       New_Res  : constant Node_Id := New_Copy_Tree (Res);
4070       Par_Spec : Node_Id;
4071       Formal   : Entity_Id;
4072
4073    begin
4074       --  If the result type is an access_to_subprogram, we must create
4075       --  new entities for its spec.
4076
4077       if Nkind (New_Res) = N_Access_Definition
4078         and then Present (Access_To_Subprogram_Definition (New_Res))
4079       then
4080          --  Provide new entities for the formals
4081
4082          Par_Spec := First (Parameter_Specifications
4083                               (Access_To_Subprogram_Definition (New_Res)));
4084          while Present (Par_Spec) loop
4085             Formal := Defining_Identifier (Par_Spec);
4086             Set_Defining_Identifier (Par_Spec,
4087               Make_Defining_Identifier (Sloc (Formal), Chars (Formal)));
4088             Next (Par_Spec);
4089          end loop;
4090       end if;
4091
4092       return New_Res;
4093    end Copy_Result_Type;
4094
4095    --------------------
4096    -- Concurrent_Ref --
4097    --------------------
4098
4099    --  The expression returned for a reference to a concurrent object has the
4100    --  form:
4101
4102    --    taskV!(name)._Task_Id
4103
4104    --  for a task, and
4105
4106    --    objectV!(name)._Object
4107
4108    --  for a protected object. For the case of an access to a concurrent
4109    --  object, there is an extra explicit dereference:
4110
4111    --    taskV!(name.all)._Task_Id
4112    --    objectV!(name.all)._Object
4113
4114    --  here taskV and objectV are the types for the associated records, which
4115    --  contain the required _Task_Id and _Object fields for tasks and protected
4116    --  objects, respectively.
4117
4118    --  For the case of a task type name, the expression is
4119
4120    --    Self;
4121
4122    --  i.e. a call to the Self function which returns precisely this Task_Id
4123
4124    --  For the case of a protected type name, the expression is
4125
4126    --    objectR
4127
4128    --  which is a renaming of the _object field of the current object
4129    --  record, passed into protected operations as a parameter.
4130
4131    function Concurrent_Ref (N : Node_Id) return Node_Id is
4132       Loc  : constant Source_Ptr := Sloc (N);
4133       Ntyp : constant Entity_Id  := Etype (N);
4134       Dtyp : Entity_Id;
4135       Sel  : Name_Id;
4136
4137       function Is_Current_Task (T : Entity_Id) return Boolean;
4138       --  Check whether the reference is to the immediately enclosing task
4139       --  type, or to an outer one (rare but legal).
4140
4141       ---------------------
4142       -- Is_Current_Task --
4143       ---------------------
4144
4145       function Is_Current_Task (T : Entity_Id) return Boolean is
4146          Scop : Entity_Id;
4147
4148       begin
4149          Scop := Current_Scope;
4150          while Present (Scop)
4151            and then Scop /= Standard_Standard
4152          loop
4153
4154             if Scop = T then
4155                return True;
4156
4157             elsif Is_Task_Type (Scop) then
4158                return False;
4159
4160             --  If this is a procedure nested within the task type, we must
4161             --  assume that it can be called from an inner task, and therefore
4162             --  cannot treat it as a local reference.
4163
4164             elsif Is_Overloadable (Scop)
4165               and then In_Open_Scopes (T)
4166             then
4167                return False;
4168
4169             else
4170                Scop := Scope (Scop);
4171             end if;
4172          end loop;
4173
4174          --  We know that we are within the task body, so should have found it
4175          --  in scope.
4176
4177          raise Program_Error;
4178       end Is_Current_Task;
4179
4180    --  Start of processing for Concurrent_Ref
4181
4182    begin
4183       if Is_Access_Type (Ntyp) then
4184          Dtyp := Designated_Type (Ntyp);
4185
4186          if Is_Protected_Type (Dtyp) then
4187             Sel := Name_uObject;
4188          else
4189             Sel := Name_uTask_Id;
4190          end if;
4191
4192          return
4193            Make_Selected_Component (Loc,
4194              Prefix =>
4195                Unchecked_Convert_To (Corresponding_Record_Type (Dtyp),
4196                  Make_Explicit_Dereference (Loc, N)),
4197              Selector_Name => Make_Identifier (Loc, Sel));
4198
4199       elsif Is_Entity_Name (N)
4200         and then Is_Concurrent_Type (Entity (N))
4201       then
4202          if Is_Task_Type (Entity (N)) then
4203
4204             if Is_Current_Task (Entity (N)) then
4205                return
4206                  Make_Function_Call (Loc,
4207                    Name => New_Reference_To (RTE (RE_Self), Loc));
4208
4209             else
4210                declare
4211                   Decl   : Node_Id;
4212                   T_Self : constant Entity_Id :=
4213                              Make_Defining_Identifier (Loc,
4214                                Chars => New_Internal_Name ('T'));
4215                   T_Body : constant Node_Id :=
4216                              Parent (Corresponding_Body (Parent (Entity (N))));
4217
4218                begin
4219                   Decl := Make_Object_Declaration (Loc,
4220                      Defining_Identifier => T_Self,
4221                      Object_Definition =>
4222                        New_Occurrence_Of (RTE (RO_ST_Task_Id), Loc),
4223                      Expression =>
4224                        Make_Function_Call (Loc,
4225                          Name => New_Reference_To (RTE (RE_Self), Loc)));
4226                   Prepend (Decl, Declarations (T_Body));
4227                   Analyze (Decl);
4228                   Set_Scope (T_Self, Entity (N));
4229                   return New_Occurrence_Of (T_Self,  Loc);
4230                end;
4231             end if;
4232
4233          else
4234             pragma Assert (Is_Protected_Type (Entity (N)));
4235
4236             return
4237               New_Reference_To (Find_Protection_Object (Current_Scope), Loc);
4238          end if;
4239
4240       else
4241          if Is_Protected_Type (Ntyp) then
4242             Sel := Name_uObject;
4243
4244          elsif Is_Task_Type (Ntyp) then
4245             Sel := Name_uTask_Id;
4246
4247          else
4248             raise Program_Error;
4249          end if;
4250
4251          return
4252            Make_Selected_Component (Loc,
4253              Prefix =>
4254                Unchecked_Convert_To (Corresponding_Record_Type (Ntyp),
4255                  New_Copy_Tree (N)),
4256              Selector_Name => Make_Identifier (Loc, Sel));
4257       end if;
4258    end Concurrent_Ref;
4259
4260    ------------------------
4261    -- Convert_Concurrent --
4262    ------------------------
4263
4264    function Convert_Concurrent
4265      (N   : Node_Id;
4266       Typ : Entity_Id) return Node_Id
4267    is
4268    begin
4269       if not Is_Concurrent_Type (Typ) then
4270          return N;
4271       else
4272          return
4273            Unchecked_Convert_To (Corresponding_Record_Type (Typ),
4274              New_Copy_Tree (N));
4275       end if;
4276    end Convert_Concurrent;
4277
4278    -------------------------------------
4279    -- Debug_Private_Data_Declarations --
4280    -------------------------------------
4281
4282    procedure Debug_Private_Data_Declarations (Decls : List_Id) is
4283       Debug_Nod : Node_Id;
4284       Decl      : Node_Id;
4285
4286    begin
4287       Decl := First (Decls);
4288       while Present (Decl)
4289         and then not Comes_From_Source (Decl)
4290       loop
4291          --  Declaration for concurrent entity _object and its access type,
4292          --  along with the entry index subtype:
4293          --    type prot_typVP is access prot_typV;
4294          --    _object : prot_typVP := prot_typV (_O);
4295          --    subtype Jnn is <Type of Index> range Low .. High;
4296
4297          if Nkind_In (Decl, N_Full_Type_Declaration, N_Object_Declaration) then
4298             Set_Debug_Info_Needed (Defining_Identifier (Decl));
4299
4300          --  Declaration for the Protection object, discriminals, privals and
4301          --  entry index constant:
4302          --    conc_typR   : protection_typ renames _object._object;
4303          --    discr_nameD : discr_typ renames _object.discr_name;
4304          --    discr_nameD : discr_typ renames _task.discr_name;
4305          --    prival_name : comp_typ  renames _object.comp_name;
4306          --    J : constant Jnn :=
4307          --          Jnn'Val (_E - <Index expression> + Jnn'Pos (Jnn'First));
4308
4309          elsif Nkind (Decl) = N_Object_Renaming_Declaration then
4310             Set_Debug_Info_Needed (Defining_Identifier (Decl));
4311             Debug_Nod := Debug_Renaming_Declaration (Decl);
4312
4313             if Present (Debug_Nod) then
4314                Insert_After (Decl, Debug_Nod);
4315             end if;
4316          end if;
4317
4318          Next (Decl);
4319       end loop;
4320    end Debug_Private_Data_Declarations;
4321
4322    ----------------------------
4323    -- Entry_Index_Expression --
4324    ----------------------------
4325
4326    function Entry_Index_Expression
4327      (Sloc  : Source_Ptr;
4328       Ent   : Entity_Id;
4329       Index : Node_Id;
4330       Ttyp  : Entity_Id) return Node_Id
4331    is
4332       Expr : Node_Id;
4333       Num  : Node_Id;
4334       Lo   : Node_Id;
4335       Hi   : Node_Id;
4336       Prev : Entity_Id;
4337       S    : Node_Id;
4338
4339    begin
4340       --  The queues of entries and entry families appear in textual order in
4341       --  the associated record. The entry index is computed as the sum of the
4342       --  number of queues for all entries that precede the designated one, to
4343       --  which is added the index expression, if this expression denotes a
4344       --  member of a family.
4345
4346       --  The following is a place holder for the count of simple entries
4347
4348       Num := Make_Integer_Literal (Sloc, 1);
4349
4350       --  We construct an expression which is a series of addition operations.
4351       --  The first operand is the number of single entries that precede this
4352       --  one, the second operand is the index value relative to the start of
4353       --  the referenced family, and the remaining operands are the lengths of
4354       --  the entry families that precede this entry, i.e. the constructed
4355       --  expression is:
4356
4357       --    number_simple_entries +
4358       --      (s'pos (index-value) - s'pos (family'first)) + 1 +
4359       --      family'length + ...
4360
4361       --  where index-value is the given index value, and s is the index
4362       --  subtype (we have to use pos because the subtype might be an
4363       --  enumeration type preventing direct subtraction). Note that the task
4364       --  entry array is one-indexed.
4365
4366       --  The upper bound of the entry family may be a discriminant, so we
4367       --  retrieve the lower bound explicitly to compute offset, rather than
4368       --  using the index subtype which may mention a discriminant.
4369
4370       if Present (Index) then
4371          S := Etype (Discrete_Subtype_Definition (Declaration_Node (Ent)));
4372
4373          Expr :=
4374            Make_Op_Add (Sloc,
4375              Left_Opnd  => Num,
4376
4377              Right_Opnd =>
4378                Family_Offset (
4379                  Sloc,
4380                  Make_Attribute_Reference (Sloc,
4381                    Attribute_Name => Name_Pos,
4382                    Prefix => New_Reference_To (Base_Type (S), Sloc),
4383                    Expressions => New_List (Relocate_Node (Index))),
4384                  Type_Low_Bound (S),
4385                  Ttyp,
4386                  False));
4387       else
4388          Expr := Num;
4389       end if;
4390
4391       --  Now add lengths of preceding entries and entry families
4392
4393       Prev := First_Entity (Ttyp);
4394
4395       while Chars (Prev) /= Chars (Ent)
4396         or else (Ekind (Prev) /= Ekind (Ent))
4397         or else not Sem_Ch6.Type_Conformant (Ent, Prev)
4398       loop
4399          if Ekind (Prev) = E_Entry then
4400             Set_Intval (Num, Intval (Num) + 1);
4401
4402          elsif Ekind (Prev) = E_Entry_Family then
4403             S :=
4404               Etype (Discrete_Subtype_Definition (Declaration_Node (Prev)));
4405             Lo := Type_Low_Bound  (S);
4406             Hi := Type_High_Bound (S);
4407
4408             Expr :=
4409               Make_Op_Add (Sloc,
4410               Left_Opnd  => Expr,
4411               Right_Opnd => Family_Size (Sloc, Hi, Lo, Ttyp, False));
4412
4413          --  Other components are anonymous types to be ignored
4414
4415          else
4416             null;
4417          end if;
4418
4419          Next_Entity (Prev);
4420       end loop;
4421
4422       return Expr;
4423    end Entry_Index_Expression;
4424
4425    ---------------------------
4426    -- Establish_Task_Master --
4427    ---------------------------
4428
4429    procedure Establish_Task_Master (N : Node_Id) is
4430       Call : Node_Id;
4431    begin
4432       if Restriction_Active (No_Task_Hierarchy) = False then
4433          Call := Build_Runtime_Call (Sloc (N), RE_Enter_Master);
4434          Prepend_To (Declarations (N), Call);
4435          Analyze (Call);
4436       end if;
4437    end Establish_Task_Master;
4438
4439    --------------------------------
4440    -- Expand_Accept_Declarations --
4441    --------------------------------
4442
4443    --  Part of the expansion of an accept statement involves the creation of
4444    --  a declaration that can be referenced from the statement sequence of
4445    --  the accept:
4446
4447    --    Ann : Address;
4448
4449    --  This declaration is inserted immediately before the accept statement
4450    --  and it is important that it be inserted before the statements of the
4451    --  statement sequence are analyzed. Thus it would be too late to create
4452    --  this declaration in the Expand_N_Accept_Statement routine, which is
4453    --  why there is a separate procedure to be called directly from Sem_Ch9.
4454
4455    --  Ann is used to hold the address of the record containing the parameters
4456    --  (see Expand_N_Entry_Call for more details on how this record is built).
4457    --  References to the parameters do an unchecked conversion of this address
4458    --  to a pointer to the required record type, and then access the field that
4459    --  holds the value of the required parameter. The entity for the address
4460    --  variable is held as the top stack element (i.e. the last element) of the
4461    --  Accept_Address stack in the corresponding entry entity, and this element
4462    --  must be set in place  before the statements are processed.
4463
4464    --  The above description applies to the case of a stand alone accept
4465    --  statement, i.e. one not appearing as part of a select alternative.
4466
4467    --  For the case of an accept that appears as part of a select alternative
4468    --  of a selective accept, we must still create the declaration right away,
4469    --  since Ann is needed immediately, but there is an important difference:
4470
4471    --    The declaration is inserted before the selective accept, not before
4472    --    the accept statement (which is not part of a list anyway, and so would
4473    --    not accommodate inserted declarations)
4474
4475    --    We only need one address variable for the entire selective accept. So
4476    --    the Ann declaration is created only for the first accept alternative,
4477    --    and subsequent accept alternatives reference the same Ann variable.
4478
4479    --  We can distinguish the two cases by seeing whether the accept statement
4480    --  is part of a list. If not, then it must be in an accept alternative.
4481
4482    --  To expand the requeue statement, a label is provided at the end of the
4483    --  accept statement or alternative of which it is a part, so that the
4484    --  statement can be skipped after the requeue is complete. This label is
4485    --  created here rather than during the expansion of the accept statement,
4486    --  because it will be needed by any requeue statements within the accept,
4487    --  which are expanded before the accept.
4488
4489    procedure Expand_Accept_Declarations (N : Node_Id; Ent : Entity_Id) is
4490       Loc    : constant Source_Ptr := Sloc (N);
4491       Stats  : constant Node_Id    := Handled_Statement_Sequence (N);
4492       Ann    : Entity_Id           := Empty;
4493       Adecl  : Node_Id;
4494       Lab_Id : Node_Id;
4495       Lab    : Node_Id;
4496       Ldecl  : Node_Id;
4497       Ldecl2 : Node_Id;
4498
4499    begin
4500       if Expander_Active then
4501
4502          --  If we have no handled statement sequence, we may need to build
4503          --  a dummy sequence consisting of a null statement. This can be
4504          --  skipped if the trivial accept optimization is permitted.
4505
4506          if not Trivial_Accept_OK
4507            and then
4508              (No (Stats) or else Null_Statements (Statements (Stats)))
4509          then
4510             Set_Handled_Statement_Sequence (N,
4511               Make_Handled_Sequence_Of_Statements (Loc,
4512                 New_List (Make_Null_Statement (Loc))));
4513          end if;
4514
4515          --  Create and declare two labels to be placed at the end of the
4516          --  accept statement. The first label is used to allow requeues to
4517          --  skip the remainder of entry processing. The second label is used
4518          --  to skip the remainder of entry processing if the rendezvous
4519          --  completes in the middle of the accept body.
4520
4521          if Present (Handled_Statement_Sequence (N)) then
4522             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
4523             Set_Entity (Lab_Id,
4524               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
4525             Lab := Make_Label (Loc, Lab_Id);
4526             Ldecl :=
4527               Make_Implicit_Label_Declaration (Loc,
4528                 Defining_Identifier  => Entity (Lab_Id),
4529                 Label_Construct      => Lab);
4530             Append (Lab, Statements (Handled_Statement_Sequence (N)));
4531
4532             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
4533             Set_Entity (Lab_Id,
4534               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
4535             Lab := Make_Label (Loc, Lab_Id);
4536             Ldecl2 :=
4537               Make_Implicit_Label_Declaration (Loc,
4538                 Defining_Identifier  => Entity (Lab_Id),
4539                 Label_Construct      => Lab);
4540             Append (Lab, Statements (Handled_Statement_Sequence (N)));
4541
4542          else
4543             Ldecl := Empty;
4544             Ldecl2 := Empty;
4545          end if;
4546
4547          --  Case of stand alone accept statement
4548
4549          if Is_List_Member (N) then
4550
4551             if Present (Handled_Statement_Sequence (N)) then
4552                Ann :=
4553                  Make_Defining_Identifier (Loc,
4554                    Chars => New_Internal_Name ('A'));
4555
4556                Adecl :=
4557                  Make_Object_Declaration (Loc,
4558                    Defining_Identifier => Ann,
4559                    Object_Definition =>
4560                      New_Reference_To (RTE (RE_Address), Loc));
4561
4562                Insert_Before (N, Adecl);
4563                Analyze (Adecl);
4564
4565                Insert_Before (N, Ldecl);
4566                Analyze (Ldecl);
4567
4568                Insert_Before (N, Ldecl2);
4569                Analyze (Ldecl2);
4570             end if;
4571
4572          --  Case of accept statement which is in an accept alternative
4573
4574          else
4575             declare
4576                Acc_Alt : constant Node_Id := Parent (N);
4577                Sel_Acc : constant Node_Id := Parent (Acc_Alt);
4578                Alt     : Node_Id;
4579
4580             begin
4581                pragma Assert (Nkind (Acc_Alt) = N_Accept_Alternative);
4582                pragma Assert (Nkind (Sel_Acc) = N_Selective_Accept);
4583
4584                --  ??? Consider a single label for select statements
4585
4586                if Present (Handled_Statement_Sequence (N)) then
4587                   Prepend (Ldecl2,
4588                      Statements (Handled_Statement_Sequence (N)));
4589                   Analyze (Ldecl2);
4590
4591                   Prepend (Ldecl,
4592                      Statements (Handled_Statement_Sequence (N)));
4593                   Analyze (Ldecl);
4594                end if;
4595
4596                --  Find first accept alternative of the selective accept. A
4597                --  valid selective accept must have at least one accept in it.
4598
4599                Alt := First (Select_Alternatives (Sel_Acc));
4600
4601                while Nkind (Alt) /= N_Accept_Alternative loop
4602                   Next (Alt);
4603                end loop;
4604
4605                --  If we are the first accept statement, then we have to create
4606                --  the Ann variable, as for the stand alone case, except that
4607                --  it is inserted before the selective accept. Similarly, a
4608                --  label for requeue expansion must be declared.
4609
4610                if N = Accept_Statement (Alt) then
4611                   Ann :=
4612                     Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4613
4614                   Adecl :=
4615                     Make_Object_Declaration (Loc,
4616                       Defining_Identifier => Ann,
4617                       Object_Definition =>
4618                         New_Reference_To (RTE (RE_Address), Loc));
4619
4620                   Insert_Before (Sel_Acc, Adecl);
4621                   Analyze (Adecl);
4622
4623                --  If we are not the first accept statement, then find the Ann
4624                --  variable allocated by the first accept and use it.
4625
4626                else
4627                   Ann :=
4628                     Node (Last_Elmt (Accept_Address
4629                       (Entity (Entry_Direct_Name (Accept_Statement (Alt))))));
4630                end if;
4631             end;
4632          end if;
4633
4634          --  Merge here with Ann either created or referenced, and Adecl
4635          --  pointing to the corresponding declaration. Remaining processing
4636          --  is the same for the two cases.
4637
4638          if Present (Ann) then
4639             Append_Elmt (Ann, Accept_Address (Ent));
4640             Set_Debug_Info_Needed (Ann);
4641          end if;
4642
4643          --  Create renaming declarations for the entry formals. Each reference
4644          --  to a formal becomes a dereference of a component of the parameter
4645          --  block, whose address is held in Ann. These declarations are
4646          --  eventually inserted into the accept block, and analyzed there so
4647          --  that they have the proper scope for gdb and do not conflict with
4648          --  other declarations.
4649
4650          if Present (Parameter_Specifications (N))
4651            and then Present (Handled_Statement_Sequence (N))
4652          then
4653             declare
4654                Comp   : Entity_Id;
4655                Decl   : Node_Id;
4656                Formal : Entity_Id;
4657                New_F  : Entity_Id;
4658
4659             begin
4660                Push_Scope (Ent);
4661                Formal := First_Formal (Ent);
4662
4663                while Present (Formal) loop
4664                   Comp  := Entry_Component (Formal);
4665                   New_F :=
4666                     Make_Defining_Identifier (Loc, Chars (Formal));
4667
4668                   Set_Etype (New_F, Etype (Formal));
4669                   Set_Scope (New_F, Ent);
4670
4671                   --  Now we set debug info needed on New_F even though it does
4672                   --  not come from source, so that the debugger will get the
4673                   --  right information for these generated names.
4674
4675                   Set_Debug_Info_Needed (New_F);
4676
4677                   if Ekind (Formal) = E_In_Parameter then
4678                      Set_Ekind (New_F, E_Constant);
4679                   else
4680                      Set_Ekind (New_F, E_Variable);
4681                      Set_Extra_Constrained (New_F, Extra_Constrained (Formal));
4682                   end if;
4683
4684                   Set_Actual_Subtype (New_F, Actual_Subtype (Formal));
4685
4686                   Decl :=
4687                     Make_Object_Renaming_Declaration (Loc,
4688                       Defining_Identifier =>
4689                         New_F,
4690                       Subtype_Mark =>
4691                         New_Reference_To (Etype (Formal), Loc),
4692                       Name =>
4693                         Make_Explicit_Dereference (Loc,
4694                           Make_Selected_Component (Loc,
4695                             Prefix =>
4696                               Unchecked_Convert_To (
4697                                 Entry_Parameters_Type (Ent),
4698                                 New_Reference_To (Ann, Loc)),
4699                             Selector_Name =>
4700                               New_Reference_To (Comp, Loc))));
4701
4702                   if No (Declarations (N)) then
4703                      Set_Declarations (N, New_List);
4704                   end if;
4705
4706                   Append (Decl, Declarations (N));
4707                   Set_Renamed_Object (Formal, New_F);
4708                   Next_Formal (Formal);
4709                end loop;
4710
4711                End_Scope;
4712             end;
4713          end if;
4714       end if;
4715    end Expand_Accept_Declarations;
4716
4717    ---------------------------------------------
4718    -- Expand_Access_Protected_Subprogram_Type --
4719    ---------------------------------------------
4720
4721    procedure Expand_Access_Protected_Subprogram_Type (N : Node_Id) is
4722       Loc    : constant Source_Ptr := Sloc (N);
4723       Comps  : List_Id;
4724       T      : constant Entity_Id  := Defining_Identifier (N);
4725       D_T    : constant Entity_Id  := Designated_Type (T);
4726       D_T2   : constant Entity_Id  := Make_Defining_Identifier (Loc,
4727                                         Chars => New_Internal_Name ('D'));
4728       E_T    : constant Entity_Id  := Make_Defining_Identifier (Loc,
4729                                         Chars => New_Internal_Name ('E'));
4730       P_List : constant List_Id    := Build_Protected_Spec
4731                                         (N, RTE (RE_Address), D_T, False);
4732       Decl1  : Node_Id;
4733       Decl2  : Node_Id;
4734       Def1   : Node_Id;
4735
4736    begin
4737       --  Create access to subprogram with full signature
4738
4739       if Etype (D_T) /= Standard_Void_Type then
4740          Def1 :=
4741            Make_Access_Function_Definition (Loc,
4742              Parameter_Specifications => P_List,
4743              Result_Definition =>
4744                Copy_Result_Type (Result_Definition (Type_Definition (N))));
4745
4746       else
4747          Def1 :=
4748            Make_Access_Procedure_Definition (Loc,
4749              Parameter_Specifications => P_List);
4750       end if;
4751
4752       Decl1 :=
4753         Make_Full_Type_Declaration (Loc,
4754           Defining_Identifier => D_T2,
4755           Type_Definition => Def1);
4756
4757       Insert_After (N, Decl1);
4758       Analyze (Decl1);
4759
4760       --  Create Equivalent_Type, a record with two components for an access to
4761       --  object and an access to subprogram.
4762
4763       Comps := New_List (
4764         Make_Component_Declaration (Loc,
4765           Defining_Identifier =>
4766             Make_Defining_Identifier (Loc, New_Internal_Name ('P')),
4767           Component_Definition =>
4768             Make_Component_Definition (Loc,
4769               Aliased_Present => False,
4770               Subtype_Indication =>
4771                 New_Occurrence_Of (RTE (RE_Address), Loc))),
4772
4773         Make_Component_Declaration (Loc,
4774           Defining_Identifier =>
4775             Make_Defining_Identifier (Loc, New_Internal_Name ('S')),
4776           Component_Definition =>
4777             Make_Component_Definition (Loc,
4778               Aliased_Present => False,
4779               Subtype_Indication => New_Occurrence_Of (D_T2, Loc))));
4780
4781       Decl2 :=
4782         Make_Full_Type_Declaration (Loc,
4783           Defining_Identifier => E_T,
4784           Type_Definition =>
4785             Make_Record_Definition (Loc,
4786               Component_List =>
4787                 Make_Component_List (Loc,
4788                   Component_Items => Comps)));
4789
4790       Insert_After (Decl1, Decl2);
4791       Analyze (Decl2);
4792       Set_Equivalent_Type (T, E_T);
4793    end Expand_Access_Protected_Subprogram_Type;
4794
4795    --------------------------
4796    -- Expand_Entry_Barrier --
4797    --------------------------
4798
4799    procedure Expand_Entry_Barrier (N : Node_Id; Ent : Entity_Id) is
4800       Cond      : constant Node_Id   :=
4801                     Condition (Entry_Body_Formal_Part (N));
4802       Prot      : constant Entity_Id := Scope (Ent);
4803       Spec_Decl : constant Node_Id   := Parent (Prot);
4804       Func      : Node_Id;
4805       B_F       : Node_Id;
4806       Body_Decl : Node_Id;
4807
4808    begin
4809       if No_Run_Time_Mode then
4810          Error_Msg_CRT ("entry barrier", N);
4811          return;
4812       end if;
4813
4814       --  The body of the entry barrier must be analyzed in the context of the
4815       --  protected object, but its scope is external to it, just as any other
4816       --  unprotected version of a protected operation. The specification has
4817       --  been produced when the protected type declaration was elaborated. We
4818       --  build the body, insert it in the enclosing scope, but analyze it in
4819       --  the current context. A more uniform approach would be to treat the
4820       --  barrier just as a protected function, and discard the protected
4821       --  version of it because it is never called.
4822
4823       if Expander_Active then
4824          B_F := Build_Barrier_Function (N, Ent, Prot);
4825          Func := Barrier_Function (Ent);
4826          Set_Corresponding_Spec (B_F, Func);
4827
4828          Body_Decl := Parent (Corresponding_Body (Spec_Decl));
4829
4830          if Nkind (Parent (Body_Decl)) = N_Subunit then
4831             Body_Decl := Corresponding_Stub (Parent (Body_Decl));
4832          end if;
4833
4834          Insert_Before_And_Analyze (Body_Decl, B_F);
4835
4836          Set_Discriminals (Spec_Decl);
4837          Set_Scope (Func, Scope (Prot));
4838
4839       else
4840          Analyze_And_Resolve (Cond, Any_Boolean);
4841       end if;
4842
4843       --  The Ravenscar profile restricts barriers to simple variables declared
4844       --  within the protected object. We also allow Boolean constants, since
4845       --  these appear in several published examples and are also allowed by
4846       --  the Aonix compiler.
4847
4848       --  Note that after analysis variables in this context will be replaced
4849       --  by the corresponding prival, that is to say a renaming of a selected
4850       --  component of the form _Object.Var. If expansion is disabled, as
4851       --  within a generic, we check that the entity appears in the current
4852       --  scope.
4853
4854       if Is_Entity_Name (Cond) then
4855
4856          --  A small optimization of useless renamings. If the scope of the
4857          --  entity of the condition is not the barrier function, then the
4858          --  condition does not reference any of the generated renamings
4859          --  within the function.
4860
4861          if Expander_Active
4862            and then Scope (Entity (Cond)) /= Func
4863          then
4864             Set_Declarations (B_F, Empty_List);
4865          end if;
4866
4867          if Entity (Cond) = Standard_False
4868               or else
4869             Entity (Cond) = Standard_True
4870          then
4871             return;
4872
4873          elsif not Expander_Active
4874            and then Scope (Entity (Cond)) = Current_Scope
4875          then
4876             return;
4877
4878          --  Check for case of _object.all.field (note that the explicit
4879          --  dereference gets inserted by analyze/expand of _object.field)
4880
4881          elsif Present (Renamed_Object (Entity (Cond)))
4882            and then
4883              Nkind (Renamed_Object (Entity (Cond))) = N_Selected_Component
4884            and then
4885              Chars
4886                (Prefix
4887                  (Prefix (Renamed_Object (Entity (Cond))))) = Name_uObject
4888          then
4889             return;
4890          end if;
4891       end if;
4892
4893       --  It is not a boolean variable or literal, so check the restriction
4894
4895       Check_Restriction (Simple_Barriers, Cond);
4896    end Expand_Entry_Barrier;
4897
4898    ------------------------------
4899    -- Expand_N_Abort_Statement --
4900    ------------------------------
4901
4902    --  Expand abort T1, T2, .. Tn; into:
4903    --    Abort_Tasks (Task_List'(1 => T1.Task_Id, 2 => T2.Task_Id ...))
4904
4905    procedure Expand_N_Abort_Statement (N : Node_Id) is
4906       Loc    : constant Source_Ptr := Sloc (N);
4907       Tlist  : constant List_Id    := Names (N);
4908       Count  : Nat;
4909       Aggr   : Node_Id;
4910       Tasknm : Node_Id;
4911
4912    begin
4913       Aggr := Make_Aggregate (Loc, Component_Associations => New_List);
4914       Count := 0;
4915
4916       Tasknm := First (Tlist);
4917
4918       while Present (Tasknm) loop
4919          Count := Count + 1;
4920
4921          --  A task interface class-wide type object is being aborted.
4922          --  Retrieve its _task_id by calling a dispatching routine.
4923
4924          if Ada_Version >= Ada_05
4925            and then Ekind (Etype (Tasknm)) = E_Class_Wide_Type
4926            and then Is_Interface (Etype (Tasknm))
4927            and then Is_Task_Interface (Etype (Tasknm))
4928          then
4929             Append_To (Component_Associations (Aggr),
4930               Make_Component_Association (Loc,
4931                 Choices => New_List (
4932                   Make_Integer_Literal (Loc, Count)),
4933                 Expression =>
4934
4935                   --  Task_Id (Tasknm._disp_get_task_id)
4936
4937                   Make_Unchecked_Type_Conversion (Loc,
4938                     Subtype_Mark =>
4939                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
4940                     Expression =>
4941                       Make_Selected_Component (Loc,
4942                         Prefix =>
4943                           New_Copy_Tree (Tasknm),
4944                         Selector_Name =>
4945                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id)))));
4946
4947          else
4948             Append_To (Component_Associations (Aggr),
4949               Make_Component_Association (Loc,
4950                 Choices => New_List (
4951                   Make_Integer_Literal (Loc, Count)),
4952                 Expression => Concurrent_Ref (Tasknm)));
4953          end if;
4954
4955          Next (Tasknm);
4956       end loop;
4957
4958       Rewrite (N,
4959         Make_Procedure_Call_Statement (Loc,
4960           Name => New_Reference_To (RTE (RE_Abort_Tasks), Loc),
4961           Parameter_Associations => New_List (
4962             Make_Qualified_Expression (Loc,
4963               Subtype_Mark => New_Reference_To (RTE (RE_Task_List), Loc),
4964               Expression => Aggr))));
4965
4966       Analyze (N);
4967    end Expand_N_Abort_Statement;
4968
4969    -------------------------------
4970    -- Expand_N_Accept_Statement --
4971    -------------------------------
4972
4973    --  This procedure handles expansion of accept statements that stand
4974    --  alone, i.e. they are not part of an accept alternative. The expansion
4975    --  of accept statement in accept alternatives is handled by the routines
4976    --  Expand_N_Accept_Alternative and Expand_N_Selective_Accept. The
4977    --  following description applies only to stand alone accept statements.
4978
4979    --  If there is no handled statement sequence, or only null statements,
4980    --  then this is called a trivial accept, and the expansion is:
4981
4982    --    Accept_Trivial (entry-index)
4983
4984    --  If there is a handled statement sequence, then the expansion is:
4985
4986    --    Ann : Address;
4987    --    {Lnn : Label}
4988
4989    --    begin
4990    --       begin
4991    --          Accept_Call (entry-index, Ann);
4992    --          Renaming_Declarations for formals
4993    --          <statement sequence from N_Accept_Statement node>
4994    --          Complete_Rendezvous;
4995    --          <<Lnn>>
4996    --
4997    --       exception
4998    --          when ... =>
4999    --             <exception handler from N_Accept_Statement node>
5000    --             Complete_Rendezvous;
5001    --          when ... =>
5002    --             <exception handler from N_Accept_Statement node>
5003    --             Complete_Rendezvous;
5004    --          ...
5005    --       end;
5006
5007    --    exception
5008    --       when all others =>
5009    --          Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
5010    --    end;
5011
5012    --  The first three declarations were already inserted ahead of the accept
5013    --  statement by the Expand_Accept_Declarations procedure, which was called
5014    --  directly from the semantics during analysis of the accept statement,
5015    --  before analyzing its contained statements.
5016
5017    --  The declarations from the N_Accept_Statement, as noted in Sinfo, come
5018    --  from possible expansion activity (the original source of course does
5019    --  not have any declarations associated with the accept statement, since
5020    --  an accept statement has no declarative part). In particular, if the
5021    --  expander is active, the first such declaration is the declaration of
5022    --  the Accept_Params_Ptr entity (see Sem_Ch9.Analyze_Accept_Statement).
5023    --
5024    --  The two blocks are merged into a single block if the inner block has
5025    --  no exception handlers, but otherwise two blocks are required, since
5026    --  exceptions might be raised in the exception handlers of the inner
5027    --  block, and Exceptional_Complete_Rendezvous must be called.
5028
5029    procedure Expand_N_Accept_Statement (N : Node_Id) is
5030       Loc     : constant Source_Ptr := Sloc (N);
5031       Stats   : constant Node_Id    := Handled_Statement_Sequence (N);
5032       Ename   : constant Node_Id    := Entry_Direct_Name (N);
5033       Eindx   : constant Node_Id    := Entry_Index (N);
5034       Eent    : constant Entity_Id  := Entity (Ename);
5035       Acstack : constant Elist_Id   := Accept_Address (Eent);
5036       Ann     : constant Entity_Id  := Node (Last_Elmt (Acstack));
5037       Ttyp    : constant Entity_Id  := Etype (Scope (Eent));
5038       Blkent  : Entity_Id;
5039       Call    : Node_Id;
5040       Block   : Node_Id;
5041
5042    --  Start of processing for Expand_N_Accept_Statement
5043
5044    begin
5045       --  If accept statement is not part of a list, then its parent must be
5046       --  an accept alternative, and, as described above, we do not do any
5047       --  expansion for such accept statements at this level.
5048
5049       if not Is_List_Member (N) then
5050          pragma Assert (Nkind (Parent (N)) = N_Accept_Alternative);
5051          return;
5052
5053       --  Trivial accept case (no statement sequence, or null statements).
5054       --  If the accept statement has declarations, then just insert them
5055       --  before the procedure call.
5056
5057       elsif Trivial_Accept_OK
5058         and then (No (Stats) or else Null_Statements (Statements (Stats)))
5059       then
5060          --  Remove declarations for renamings, because the parameter block
5061          --  will not be assigned.
5062
5063          declare
5064             D      : Node_Id;
5065             Next_D : Node_Id;
5066
5067          begin
5068             D := First (Declarations (N));
5069
5070             while Present (D) loop
5071                Next_D := Next (D);
5072                if Nkind (D) = N_Object_Renaming_Declaration then
5073                   Remove (D);
5074                end if;
5075
5076                D := Next_D;
5077             end loop;
5078          end;
5079
5080          if Present (Declarations (N)) then
5081             Insert_Actions (N, Declarations (N));
5082          end if;
5083
5084          Rewrite (N,
5085            Make_Procedure_Call_Statement (Loc,
5086              Name => New_Reference_To (RTE (RE_Accept_Trivial), Loc),
5087              Parameter_Associations => New_List (
5088                Entry_Index_Expression (Loc, Entity (Ename), Eindx, Ttyp))));
5089
5090          Analyze (N);
5091
5092          --  Discard Entry_Address that was created for it, so it will not be
5093          --  emitted if this accept statement is in the statement part of a
5094          --  delay alternative.
5095
5096          if Present (Stats) then
5097             Remove_Last_Elmt (Acstack);
5098          end if;
5099
5100       --  Case of statement sequence present
5101
5102       else
5103          --  Construct the block, using the declarations from the accept
5104          --  statement if any to initialize the declarations of the block.
5105
5106          Blkent := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5107          Set_Ekind (Blkent, E_Block);
5108          Set_Etype (Blkent, Standard_Void_Type);
5109          Set_Scope (Blkent, Current_Scope);
5110
5111          Block :=
5112            Make_Block_Statement (Loc,
5113              Identifier                 => New_Reference_To (Blkent, Loc),
5114              Declarations               => Declarations (N),
5115              Handled_Statement_Sequence => Build_Accept_Body (N));
5116
5117          --  Prepend call to Accept_Call to main statement sequence If the
5118          --  accept has exception handlers, the statement sequence is wrapped
5119          --  in a block. Insert call and renaming declarations in the
5120          --  declarations of the block, so they are elaborated before the
5121          --  handlers.
5122
5123          Call :=
5124            Make_Procedure_Call_Statement (Loc,
5125              Name => New_Reference_To (RTE (RE_Accept_Call), Loc),
5126              Parameter_Associations => New_List (
5127                Entry_Index_Expression (Loc, Entity (Ename), Eindx, Ttyp),
5128                New_Reference_To (Ann, Loc)));
5129
5130          if Parent (Stats) = N then
5131             Prepend (Call, Statements (Stats));
5132          else
5133             Set_Declarations
5134               (Parent (Stats),
5135                 New_List (Call));
5136          end if;
5137
5138          Analyze (Call);
5139
5140          Push_Scope (Blkent);
5141
5142          declare
5143             D      : Node_Id;
5144             Next_D : Node_Id;
5145             Typ    : Entity_Id;
5146
5147          begin
5148             D := First (Declarations (N));
5149             while Present (D) loop
5150                Next_D := Next (D);
5151
5152                if Nkind (D) = N_Object_Renaming_Declaration then
5153
5154                   --  The renaming declarations for the formals were created
5155                   --  during analysis of the accept statement, and attached to
5156                   --  the list of declarations. Place them now in the context
5157                   --  of the accept block or subprogram.
5158
5159                   Remove (D);
5160                   Typ := Entity (Subtype_Mark (D));
5161                   Insert_After (Call, D);
5162                   Analyze (D);
5163
5164                   --  If the formal is class_wide, it does not have an actual
5165                   --  subtype. The analysis of the renaming declaration creates
5166                   --  one, but we need to retain the class-wide nature of the
5167                   --  entity.
5168
5169                   if Is_Class_Wide_Type (Typ) then
5170                      Set_Etype (Defining_Identifier (D), Typ);
5171                   end if;
5172
5173                end if;
5174
5175                D := Next_D;
5176             end loop;
5177          end;
5178
5179          End_Scope;
5180
5181          --  Replace the accept statement by the new block
5182
5183          Rewrite (N, Block);
5184          Analyze (N);
5185
5186          --  Last step is to unstack the Accept_Address value
5187
5188          Remove_Last_Elmt (Acstack);
5189       end if;
5190    end Expand_N_Accept_Statement;
5191
5192    ----------------------------------
5193    -- Expand_N_Asynchronous_Select --
5194    ----------------------------------
5195
5196    --  This procedure assumes that the trigger statement is an entry call or
5197    --  a dispatching procedure call. A delay alternative should already have
5198    --  been expanded into an entry call to the appropriate delay object Wait
5199    --  entry.
5200
5201    --  If the trigger is a task entry call, the select is implemented with
5202    --  a Task_Entry_Call:
5203
5204    --    declare
5205    --       B : Boolean;
5206    --       C : Boolean;
5207    --       P : parms := (parm, parm, parm);
5208
5209    --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
5210
5211    --       procedure _clean is
5212    --       begin
5213    --          ...
5214    --          Cancel_Task_Entry_Call (C);
5215    --          ...
5216    --       end _clean;
5217
5218    --    begin
5219    --       Abort_Defer;
5220    --       Task_Entry_Call
5221    --         (<acceptor-task>,    --  Acceptor
5222    --          <entry-index>,      --  E
5223    --          P'Address,          --  Uninterpreted_Data
5224    --          Asynchronous_Call,  --  Mode
5225    --          B);                 --  Rendezvous_Successful
5226
5227    --       begin
5228    --          begin
5229    --             Abort_Undefer;
5230    --             <abortable-part>
5231    --          at end
5232    --             _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5233    --          end;
5234    --       exception
5235    --          when Abort_Signal => Abort_Undefer;
5236    --       end;
5237
5238    --       parm := P.param;
5239    --       parm := P.param;
5240    --       ...
5241    --       if not C then
5242    --          <triggered-statements>
5243    --       end if;
5244    --    end;
5245
5246    --  Note that Build_Simple_Entry_Call is used to expand the entry of the
5247    --  asynchronous entry call (by Expand_N_Entry_Call_Statement procedure)
5248    --  as follows:
5249
5250    --    declare
5251    --       P : parms := (parm, parm, parm);
5252    --    begin
5253    --       Call_Simple (acceptor-task, entry-index, P'Address);
5254    --       parm := P.param;
5255    --       parm := P.param;
5256    --       ...
5257    --    end;
5258
5259    --  so the task at hand is to convert the latter expansion into the former
5260
5261    --  If the trigger is a protected entry call, the select is implemented
5262    --  with Protected_Entry_Call:
5263
5264    --  declare
5265    --     P   : E1_Params := (param, param, param);
5266    --     Bnn : Communications_Block;
5267
5268    --  begin
5269    --     declare
5270
5271    --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
5272
5273    --        procedure _clean is
5274    --        begin
5275    --           ...
5276    --           if Enqueued (Bnn) then
5277    --              Cancel_Protected_Entry_Call (Bnn);
5278    --           end if;
5279    --           ...
5280    --        end _clean;
5281
5282    --     begin
5283    --        begin
5284    --           Protected_Entry_Call
5285    --             (po._object'Access,  --  Object
5286    --              <entry index>,      --  E
5287    --              P'Address,          --  Uninterpreted_Data
5288    --              Asynchronous_Call,  --  Mode
5289    --              Bnn);               --  Block
5290
5291    --           if Enqueued (Bnn) then
5292    --              <abortable-part>
5293    --           end if;
5294    --        at end
5295    --           _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5296    --        end;
5297    --     exception
5298    --        when Abort_Signal => Abort_Undefer;
5299    --     end;
5300
5301    --     if not Cancelled (Bnn) then
5302    --        <triggered-statements>
5303    --     end if;
5304    --  end;
5305
5306    --  Build_Simple_Entry_Call is used to expand the all to a simple protected
5307    --  entry call:
5308
5309    --  declare
5310    --     P   : E1_Params := (param, param, param);
5311    --     Bnn : Communications_Block;
5312
5313    --  begin
5314    --     Protected_Entry_Call
5315    --       (po._object'Access,  --  Object
5316    --        <entry index>,      --  E
5317    --        P'Address,          --  Uninterpreted_Data
5318    --        Simple_Call,        --  Mode
5319    --        Bnn);               --  Block
5320    --     parm := P.param;
5321    --     parm := P.param;
5322    --       ...
5323    --  end;
5324
5325    --  Ada 2005 (AI-345): If the trigger is a dispatching call, the select is
5326    --  expanded into:
5327
5328    --    declare
5329    --       B   : Boolean := False;
5330    --       Bnn : Communication_Block;
5331    --       C   : Ada.Tags.Prim_Op_Kind;
5332    --       D   : System.Storage_Elements.Dummy_Communication_Block;
5333    --       K   : Ada.Tags.Tagged_Kind :=
5334    --               Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
5335    --       P   : Parameters := (Param1 .. ParamN);
5336    --       S   : Integer;
5337    --       U   : Boolean;
5338
5339    --    begin
5340    --       if K = Ada.Tags.TK_Limited_Tagged then
5341    --          <dispatching-call>;
5342    --          <triggering-statements>;
5343
5344    --       else
5345    --          S :=
5346    --            Ada.Tags.Get_Offset_Index
5347    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
5348
5349    --          _Disp_Get_Prim_Op_Kind (<object>, S, C);
5350
5351    --          if C = POK_Protected_Entry then
5352    --             declare
5353    --                procedure _clean is
5354    --                begin
5355    --                   if Enqueued (Bnn) then
5356    --                      Cancel_Protected_Entry_Call (Bnn);
5357    --                   end if;
5358    --                end _clean;
5359
5360    --             begin
5361    --                begin
5362    --                   _Disp_Asynchronous_Select
5363    --                     (<object>, S, P'Address, D, B);
5364    --                   Bnn := Communication_Block (D);
5365
5366    --                   Param1 := P.Param1;
5367    --                   ...
5368    --                   ParamN := P.ParamN;
5369
5370    --                   if Enqueued (Bnn) then
5371    --                      <abortable-statements>
5372    --                   end if;
5373    --                at end
5374    --                   _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5375    --                end;
5376    --             exception
5377    --                when Abort_Signal => Abort_Undefer;
5378    --             end;
5379
5380    --             if not Cancelled (Bnn) then
5381    --                <triggering-statements>
5382    --             end if;
5383
5384    --          elsif C = POK_Task_Entry then
5385    --             declare
5386    --                procedure _clean is
5387    --                begin
5388    --                   Cancel_Task_Entry_Call (U);
5389    --                end _clean;
5390
5391    --             begin
5392    --                Abort_Defer;
5393
5394    --                _Disp_Asynchronous_Select
5395    --                  (<object>, S, P'Address, D, B);
5396    --                Bnn := Communication_Bloc (D);
5397
5398    --                Param1 := P.Param1;
5399    --                ...
5400    --                ParamN := P.ParamN;
5401
5402    --                begin
5403    --                   begin
5404    --                      Abort_Undefer;
5405    --                      <abortable-statements>
5406    --                   at end
5407    --                      _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5408    --                   end;
5409    --                exception
5410    --                   when Abort_Signal => Abort_Undefer;
5411    --                end;
5412
5413    --                if not U then
5414    --                   <triggering-statements>
5415    --                end if;
5416    --             end;
5417
5418    --          else
5419    --             <dispatching-call>;
5420    --             <triggering-statements>
5421    --          end if;
5422    --       end if;
5423    --    end;
5424
5425    --  The job is to convert this to the asynchronous form
5426
5427    --  If the trigger is a delay statement, it will have been expanded into a
5428    --  call to one of the GNARL delay procedures. This routine will convert
5429    --  this into a protected entry call on a delay object and then continue
5430    --  processing as for a protected entry call trigger. This requires
5431    --  declaring a Delay_Block object and adding a pointer to this object to
5432    --  the parameter list of the delay procedure to form the parameter list of
5433    --  the entry call. This object is used by the runtime to queue the delay
5434    --  request.
5435
5436    --  For a description of the use of P and the assignments after the call,
5437    --  see Expand_N_Entry_Call_Statement.
5438
5439    procedure Expand_N_Asynchronous_Select (N : Node_Id) is
5440       Loc    : constant Source_Ptr := Sloc (N);
5441       Abrt   : constant Node_Id    := Abortable_Part (N);
5442       Astats : constant List_Id    := Statements (Abrt);
5443       Trig   : constant Node_Id    := Triggering_Alternative (N);
5444       Tstats : constant List_Id    := Statements (Trig);
5445
5446       Abort_Block_Ent   : Entity_Id;
5447       Abortable_Block   : Node_Id;
5448       Actuals           : List_Id;
5449       Blk_Ent           : Entity_Id;
5450       Blk_Typ           : Entity_Id;
5451       Call              : Node_Id;
5452       Call_Ent          : Entity_Id;
5453       Cancel_Param      : Entity_Id;
5454       Cleanup_Block     : Node_Id;
5455       Cleanup_Block_Ent : Entity_Id;
5456       Cleanup_Stmts     : List_Id;
5457       Conc_Typ_Stmts    : List_Id;
5458       Concval           : Node_Id;
5459       Dblock_Ent        : Entity_Id;
5460       Decl              : Node_Id;
5461       Decls             : List_Id;
5462       Ecall             : Node_Id;
5463       Ename             : Node_Id;
5464       Enqueue_Call      : Node_Id;
5465       Formals           : List_Id;
5466       Hdle              : List_Id;
5467       Index             : Node_Id;
5468       Lim_Typ_Stmts     : List_Id;
5469       N_Orig            : Node_Id;
5470       Obj               : Entity_Id;
5471       Param             : Node_Id;
5472       Params            : List_Id;
5473       Pdef              : Entity_Id;
5474       ProtE_Stmts       : List_Id;
5475       ProtP_Stmts       : List_Id;
5476       Stmt              : Node_Id;
5477       Stmts             : List_Id;
5478       Target_Undefer    : RE_Id;
5479       TaskE_Stmts       : List_Id;
5480       Undefer_Args      : List_Id := No_List;
5481
5482       B   : Entity_Id;  --  Call status flag
5483       Bnn : Entity_Id;  --  Communication block
5484       C   : Entity_Id;  --  Call kind
5485       K   : Entity_Id;  --  Tagged kind
5486       P   : Entity_Id;  --  Parameter block
5487       S   : Entity_Id;  --  Primitive operation slot
5488       T   : Entity_Id;  --  Additional status flag
5489
5490    begin
5491       Blk_Ent := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5492       Ecall   := Triggering_Statement (Trig);
5493
5494       --  The arguments in the call may require dynamic allocation, and the
5495       --  call statement may have been transformed into a block. The block
5496       --  may contain additional declarations for internal entities, and the
5497       --  original call is found by sequential search.
5498
5499       if Nkind (Ecall) = N_Block_Statement then
5500          Ecall := First (Statements (Handled_Statement_Sequence (Ecall)));
5501          while not Nkind_In (Ecall, N_Procedure_Call_Statement,
5502                                     N_Entry_Call_Statement)
5503          loop
5504             Next (Ecall);
5505          end loop;
5506       end if;
5507
5508       --  This is either a dispatching call or a delay statement used as a
5509       --  trigger which was expanded into a procedure call.
5510
5511       if Nkind (Ecall) = N_Procedure_Call_Statement then
5512          if Ada_Version >= Ada_05
5513            and then
5514              (No (Original_Node (Ecall))
5515                 or else not Nkind_In (Original_Node (Ecall),
5516                                         N_Delay_Relative_Statement,
5517                                         N_Delay_Until_Statement))
5518          then
5519             Extract_Dispatching_Call (Ecall, Call_Ent, Obj, Actuals, Formals);
5520
5521             Decls := New_List;
5522             Stmts := New_List;
5523
5524             --  Call status flag processing, generate:
5525             --    B : Boolean := False;
5526
5527             B := Build_B (Loc, Decls);
5528
5529             --  Communication block processing, generate:
5530             --    Bnn : Communication_Block;
5531
5532             Bnn := Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
5533
5534             Append_To (Decls,
5535               Make_Object_Declaration (Loc,
5536                 Defining_Identifier =>
5537                   Bnn,
5538                 Object_Definition =>
5539                   New_Reference_To (RTE (RE_Communication_Block), Loc)));
5540
5541             --  Call kind processing, generate:
5542             --    C : Ada.Tags.Prim_Op_Kind;
5543
5544             C := Build_C (Loc, Decls);
5545
5546             --  Tagged kind processing, generate:
5547             --    K : Ada.Tags.Tagged_Kind :=
5548             --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
5549
5550             --  Dummy communication block, generate:
5551             --    D : Dummy_Communication_Block;
5552
5553             Append_To (Decls,
5554               Make_Object_Declaration (Loc,
5555                 Defining_Identifier =>
5556                   Make_Defining_Identifier (Loc, Name_uD),
5557                 Object_Definition =>
5558                   New_Reference_To (
5559                     RTE (RE_Dummy_Communication_Block), Loc)));
5560
5561             K := Build_K (Loc, Decls, Obj);
5562
5563             --  Parameter block processing
5564
5565             Blk_Typ := Build_Parameter_Block
5566                          (Loc, Actuals, Formals, Decls);
5567             P       := Parameter_Block_Pack
5568                          (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
5569
5570             --  Dispatch table slot processing, generate:
5571             --    S : Integer;
5572
5573             S := Build_S (Loc, Decls);
5574
5575             --  Additional status flag processing, generate:
5576
5577             T := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
5578
5579             Append_To (Decls,
5580               Make_Object_Declaration (Loc,
5581                 Defining_Identifier =>
5582                   T,
5583                 Object_Definition =>
5584                   New_Reference_To (Standard_Boolean, Loc)));
5585
5586             ------------------------------
5587             -- Protected entry handling --
5588             ------------------------------
5589
5590             --  Generate:
5591             --    Param1 := P.Param1;
5592             --    ...
5593             --    ParamN := P.ParamN;
5594
5595             Cleanup_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
5596
5597             --  Generate:
5598             --    Bnn := Communication_Block (D);
5599
5600             Prepend_To (Cleanup_Stmts,
5601               Make_Assignment_Statement (Loc,
5602                 Name =>
5603                   New_Reference_To (Bnn, Loc),
5604                 Expression =>
5605                   Make_Unchecked_Type_Conversion (Loc,
5606                     Subtype_Mark =>
5607                       New_Reference_To (RTE (RE_Communication_Block), Loc),
5608                     Expression =>
5609                       Make_Identifier (Loc, Name_uD))));
5610
5611             --  Generate:
5612             --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
5613
5614             Prepend_To (Cleanup_Stmts,
5615               Make_Procedure_Call_Statement (Loc,
5616                 Name =>
5617                   New_Reference_To (
5618                     Find_Prim_Op (Etype (Etype (Obj)),
5619                       Name_uDisp_Asynchronous_Select),
5620                     Loc),
5621                 Parameter_Associations =>
5622                   New_List (
5623                     New_Copy_Tree (Obj),             --  <object>
5624                     New_Reference_To (S, Loc),       --  S
5625                     Make_Attribute_Reference (Loc,   --  P'Address
5626                       Prefix =>
5627                         New_Reference_To (P, Loc),
5628                       Attribute_Name =>
5629                         Name_Address),
5630                     Make_Identifier (Loc, Name_uD),  --  D
5631                     New_Reference_To (B, Loc))));    --  B
5632
5633             --  Generate:
5634             --    if Enqueued (Bnn) then
5635             --       <abortable-statements>
5636             --    end if;
5637
5638             Append_To (Cleanup_Stmts,
5639               Make_If_Statement (Loc,
5640                 Condition =>
5641                   Make_Function_Call (Loc,
5642                     Name =>
5643                       New_Reference_To (RTE (RE_Enqueued), Loc),
5644                     Parameter_Associations =>
5645                       New_List (
5646                         New_Reference_To (Bnn, Loc))),
5647
5648                 Then_Statements =>
5649                   New_Copy_List_Tree (Astats)));
5650
5651             --  Wrap the statements in a block. Exp_Ch7.Expand_Cleanup_Actions
5652             --  will then generate a _clean for the communication block Bnn.
5653
5654             --  Generate:
5655             --    declare
5656             --       procedure _clean is
5657             --       begin
5658             --          if Enqueued (Bnn) then
5659             --             Cancel_Protected_Entry_Call (Bnn);
5660             --          end if;
5661             --       end _clean;
5662             --    begin
5663             --       Cleanup_Stmts
5664             --    at end
5665             --       _clean;
5666             --    end;
5667
5668             Cleanup_Block_Ent :=
5669               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
5670
5671             Cleanup_Block :=
5672               Build_Cleanup_Block (Loc, Cleanup_Block_Ent, Cleanup_Stmts, Bnn);
5673
5674             --  Wrap the cleanup block in an exception handling block
5675
5676             --  Generate:
5677             --    begin
5678             --       Cleanup_Block
5679             --    exception
5680             --       when Abort_Signal => Abort_Undefer;
5681             --    end;
5682
5683             Abort_Block_Ent :=
5684               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5685
5686             ProtE_Stmts :=
5687               New_List (
5688                 Make_Implicit_Label_Declaration (Loc,
5689                   Defining_Identifier =>
5690                     Abort_Block_Ent),
5691
5692                 Build_Abort_Block
5693                   (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
5694
5695             --  Generate:
5696             --    if not Cancelled (Bnn) then
5697             --       <triggering-statements>
5698             --    end if;
5699
5700             Append_To (ProtE_Stmts,
5701               Make_If_Statement (Loc,
5702                 Condition =>
5703                   Make_Op_Not (Loc,
5704                     Right_Opnd =>
5705                       Make_Function_Call (Loc,
5706                         Name =>
5707                           New_Reference_To (RTE (RE_Cancelled), Loc),
5708                         Parameter_Associations =>
5709                           New_List (
5710                             New_Reference_To (Bnn, Loc)))),
5711
5712                 Then_Statements =>
5713                   New_Copy_List_Tree (Tstats)));
5714
5715             -------------------------
5716             -- Task entry handling --
5717             -------------------------
5718
5719             --  Generate:
5720             --    Param1 := P.Param1;
5721             --    ...
5722             --    ParamN := P.ParamN;
5723
5724             TaskE_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
5725
5726             --  Generate:
5727             --    Bnn := Communication_Block (D);
5728
5729             Append_To (TaskE_Stmts,
5730               Make_Assignment_Statement (Loc,
5731                 Name =>
5732                   New_Reference_To (Bnn, Loc),
5733                 Expression =>
5734                   Make_Unchecked_Type_Conversion (Loc,
5735                     Subtype_Mark =>
5736                       New_Reference_To (RTE (RE_Communication_Block), Loc),
5737                     Expression =>
5738                       Make_Identifier (Loc, Name_uD))));
5739
5740             --  Generate:
5741             --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
5742
5743             Prepend_To (TaskE_Stmts,
5744               Make_Procedure_Call_Statement (Loc,
5745                 Name =>
5746                   New_Reference_To (
5747                     Find_Prim_Op (Etype (Etype (Obj)),
5748                       Name_uDisp_Asynchronous_Select),
5749                     Loc),
5750                 Parameter_Associations =>
5751                   New_List (
5752                     New_Copy_Tree (Obj),             --  <object>
5753                     New_Reference_To (S, Loc),       --  S
5754                     Make_Attribute_Reference (Loc,   --  P'Address
5755                       Prefix =>
5756                         New_Reference_To (P, Loc),
5757                       Attribute_Name =>
5758                         Name_Address),
5759                     Make_Identifier (Loc, Name_uD),  --  D
5760                     New_Reference_To (B, Loc))));    --  B
5761
5762             --  Generate:
5763             --    Abort_Defer;
5764
5765             Prepend_To (TaskE_Stmts,
5766               Make_Procedure_Call_Statement (Loc,
5767                 Name =>
5768                   New_Reference_To (RTE (RE_Abort_Defer), Loc),
5769                 Parameter_Associations =>
5770                   No_List));
5771
5772             --  Generate:
5773             --    Abort_Undefer;
5774             --    <abortable-statements>
5775
5776             Cleanup_Stmts := New_Copy_List_Tree (Astats);
5777
5778             Prepend_To (Cleanup_Stmts,
5779               Make_Procedure_Call_Statement (Loc,
5780                 Name =>
5781                   New_Reference_To (RTE (RE_Abort_Undefer), Loc),
5782                 Parameter_Associations =>
5783                   No_List));
5784
5785             --  Wrap the statements in a block. Exp_Ch7.Expand_Cleanup_Actions
5786             --  will generate a _clean for the additional status flag.
5787
5788             --  Generate:
5789             --    declare
5790             --       procedure _clean is
5791             --       begin
5792             --          Cancel_Task_Entry_Call (U);
5793             --       end _clean;
5794             --    begin
5795             --       Cleanup_Stmts
5796             --    at end
5797             --       _clean;
5798             --    end;
5799
5800             Cleanup_Block_Ent :=
5801               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
5802
5803             Cleanup_Block :=
5804               Build_Cleanup_Block (Loc, Cleanup_Block_Ent, Cleanup_Stmts, T);
5805
5806             --  Wrap the cleanup block in an exception handling block
5807
5808             --  Generate:
5809             --    begin
5810             --       Cleanup_Block
5811             --    exception
5812             --       when Abort_Signal => Abort_Undefer;
5813             --    end;
5814
5815             Abort_Block_Ent :=
5816               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5817
5818             Append_To (TaskE_Stmts,
5819               Make_Implicit_Label_Declaration (Loc,
5820                 Defining_Identifier =>
5821                   Abort_Block_Ent));
5822
5823             Append_To (TaskE_Stmts,
5824               Build_Abort_Block
5825                 (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
5826
5827             --  Generate:
5828             --    if not T then
5829             --       <triggering-statements>
5830             --    end if;
5831
5832             Append_To (TaskE_Stmts,
5833               Make_If_Statement (Loc,
5834                 Condition =>
5835                   Make_Op_Not (Loc,
5836                     Right_Opnd =>
5837                       New_Reference_To (T, Loc)),
5838
5839                 Then_Statements =>
5840                   New_Copy_List_Tree (Tstats)));
5841
5842             ----------------------------------
5843             -- Protected procedure handling --
5844             ----------------------------------
5845
5846             --  Generate:
5847             --    <dispatching-call>;
5848             --    <triggering-statements>
5849
5850             ProtP_Stmts := New_Copy_List_Tree (Tstats);
5851             Prepend_To (ProtP_Stmts, New_Copy_Tree (Ecall));
5852
5853             --  Generate:
5854             --    S := Ada.Tags.Get_Offset_Index
5855             --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
5856
5857             Conc_Typ_Stmts :=
5858               New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
5859
5860             --  Generate:
5861             --    _Disp_Get_Prim_Op_Kind (<object>, S, C);
5862
5863             Append_To (Conc_Typ_Stmts,
5864               Make_Procedure_Call_Statement (Loc,
5865                 Name =>
5866                   New_Reference_To (
5867                     Find_Prim_Op (Etype (Etype (Obj)),
5868                       Name_uDisp_Get_Prim_Op_Kind),
5869                     Loc),
5870                 Parameter_Associations =>
5871                   New_List (
5872                     New_Copy_Tree (Obj),
5873                     New_Reference_To (S, Loc),
5874                     New_Reference_To (C, Loc))));
5875
5876             --  Generate:
5877             --    if C = POK_Procedure_Entry then
5878             --       ProtE_Stmts
5879             --    elsif C = POK_Task_Entry then
5880             --       TaskE_Stmts
5881             --    else
5882             --       ProtP_Stmts
5883             --    end if;
5884
5885             Append_To (Conc_Typ_Stmts,
5886               Make_If_Statement (Loc,
5887                 Condition =>
5888                   Make_Op_Eq (Loc,
5889                     Left_Opnd =>
5890                       New_Reference_To (C, Loc),
5891                     Right_Opnd =>
5892                       New_Reference_To (RTE (RE_POK_Protected_Entry), Loc)),
5893
5894                 Then_Statements =>
5895                   ProtE_Stmts,
5896
5897                 Elsif_Parts =>
5898                   New_List (
5899                     Make_Elsif_Part (Loc,
5900                       Condition =>
5901                         Make_Op_Eq (Loc,
5902                           Left_Opnd =>
5903                             New_Reference_To (C, Loc),
5904                           Right_Opnd =>
5905                             New_Reference_To (RTE (RE_POK_Task_Entry), Loc)),
5906
5907                       Then_Statements =>
5908                         TaskE_Stmts)),
5909
5910                 Else_Statements =>
5911                   ProtP_Stmts));
5912
5913             --  Generate:
5914             --    <dispatching-call>;
5915             --    <triggering-statements>
5916
5917             Lim_Typ_Stmts := New_Copy_List_Tree (Tstats);
5918             Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (Ecall));
5919
5920             --  Generate:
5921             --    if K = Ada.Tags.TK_Limited_Tagged then
5922             --       Lim_Typ_Stmts
5923             --    else
5924             --       Conc_Typ_Stmts
5925             --    end if;
5926
5927             Append_To (Stmts,
5928               Make_If_Statement (Loc,
5929                 Condition =>
5930                    Make_Op_Eq (Loc,
5931                      Left_Opnd =>
5932                        New_Reference_To (K, Loc),
5933                      Right_Opnd =>
5934                        New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
5935
5936                 Then_Statements =>
5937                   Lim_Typ_Stmts,
5938
5939                 Else_Statements =>
5940                   Conc_Typ_Stmts));
5941
5942             Rewrite (N,
5943               Make_Block_Statement (Loc,
5944                 Declarations =>
5945                   Decls,
5946                 Handled_Statement_Sequence =>
5947                   Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
5948
5949             Analyze (N);
5950             return;
5951
5952          --  Delay triggering statement processing
5953
5954          else
5955             --  Add a Delay_Block object to the parameter list of the delay
5956             --  procedure to form the parameter list of the Wait entry call.
5957
5958             Dblock_Ent :=
5959               Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
5960
5961             Pdef := Entity (Name (Ecall));
5962
5963             if Is_RTE (Pdef, RO_CA_Delay_For) then
5964                Enqueue_Call :=
5965                  New_Reference_To (RTE (RE_Enqueue_Duration), Loc);
5966
5967             elsif Is_RTE (Pdef, RO_CA_Delay_Until) then
5968                Enqueue_Call :=
5969                  New_Reference_To (RTE (RE_Enqueue_Calendar), Loc);
5970
5971             else pragma Assert (Is_RTE (Pdef, RO_RT_Delay_Until));
5972                Enqueue_Call := New_Reference_To (RTE (RE_Enqueue_RT), Loc);
5973             end if;
5974
5975             Append_To (Parameter_Associations (Ecall),
5976               Make_Attribute_Reference (Loc,
5977                 Prefix => New_Reference_To (Dblock_Ent, Loc),
5978                 Attribute_Name => Name_Unchecked_Access));
5979
5980             --  Create the inner block to protect the abortable part
5981
5982             Hdle := New_List (
5983               Make_Implicit_Exception_Handler (Loc,
5984                 Exception_Choices =>
5985                   New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
5986                 Statements => New_List (
5987                   Make_Procedure_Call_Statement (Loc,
5988                     Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
5989
5990             Prepend_To (Astats,
5991               Make_Procedure_Call_Statement (Loc,
5992                 Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)));
5993
5994             Abortable_Block :=
5995               Make_Block_Statement (Loc,
5996                 Identifier => New_Reference_To (Blk_Ent, Loc),
5997                 Handled_Statement_Sequence =>
5998                   Make_Handled_Sequence_Of_Statements (Loc,
5999                     Statements => Astats),
6000                 Has_Created_Identifier => True,
6001                 Is_Asynchronous_Call_Block => True);
6002
6003             --  Append call to if Enqueue (When, DB'Unchecked_Access) then
6004
6005             Rewrite (Ecall,
6006               Make_Implicit_If_Statement (N,
6007                 Condition => Make_Function_Call (Loc,
6008                   Name => Enqueue_Call,
6009                   Parameter_Associations => Parameter_Associations (Ecall)),
6010                 Then_Statements =>
6011                   New_List (Make_Block_Statement (Loc,
6012                     Handled_Statement_Sequence =>
6013                       Make_Handled_Sequence_Of_Statements (Loc,
6014                         Statements => New_List (
6015                           Make_Implicit_Label_Declaration (Loc,
6016                             Defining_Identifier => Blk_Ent,
6017                             Label_Construct     => Abortable_Block),
6018                           Abortable_Block),
6019                         Exception_Handlers => Hdle)))));
6020
6021             Stmts := New_List (Ecall);
6022
6023             --  Construct statement sequence for new block
6024
6025             Append_To (Stmts,
6026               Make_Implicit_If_Statement (N,
6027                 Condition => Make_Function_Call (Loc,
6028                   Name => New_Reference_To (
6029                     RTE (RE_Timed_Out), Loc),
6030                   Parameter_Associations => New_List (
6031                     Make_Attribute_Reference (Loc,
6032                       Prefix => New_Reference_To (Dblock_Ent, Loc),
6033                       Attribute_Name => Name_Unchecked_Access))),
6034                 Then_Statements => Tstats));
6035
6036             --  The result is the new block
6037
6038             Set_Entry_Cancel_Parameter (Blk_Ent, Dblock_Ent);
6039
6040             Rewrite (N,
6041               Make_Block_Statement (Loc,
6042                 Declarations => New_List (
6043                   Make_Object_Declaration (Loc,
6044                     Defining_Identifier => Dblock_Ent,
6045                     Aliased_Present => True,
6046                     Object_Definition => New_Reference_To (
6047                       RTE (RE_Delay_Block), Loc))),
6048
6049                 Handled_Statement_Sequence =>
6050                   Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6051
6052             Analyze (N);
6053             return;
6054          end if;
6055
6056       else
6057          N_Orig := N;
6058       end if;
6059
6060       Extract_Entry (Ecall, Concval, Ename, Index);
6061       Build_Simple_Entry_Call (Ecall, Concval, Ename, Index);
6062
6063       Stmts := Statements (Handled_Statement_Sequence (Ecall));
6064       Decls := Declarations (Ecall);
6065
6066       if Is_Protected_Type (Etype (Concval)) then
6067
6068          --  Get the declarations of the block expanded from the entry call
6069
6070          Decl := First (Decls);
6071          while Present (Decl)
6072            and then
6073              (Nkind (Decl) /= N_Object_Declaration
6074                or else not Is_RTE (Etype (Object_Definition (Decl)),
6075                                    RE_Communication_Block))
6076          loop
6077             Next (Decl);
6078          end loop;
6079
6080          pragma Assert (Present (Decl));
6081          Cancel_Param := Defining_Identifier (Decl);
6082
6083          --  Change the mode of the Protected_Entry_Call call
6084
6085          --  Protected_Entry_Call (
6086          --    Object => po._object'Access,
6087          --    E => <entry index>;
6088          --    Uninterpreted_Data => P'Address;
6089          --    Mode => Asynchronous_Call;
6090          --    Block => Bnn);
6091
6092          Stmt := First (Stmts);
6093
6094          --  Skip assignments to temporaries created for in-out parameters
6095
6096          --  This makes unwarranted assumptions about the shape of the expanded
6097          --  tree for the call, and should be cleaned up ???
6098
6099          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6100             Next (Stmt);
6101          end loop;
6102
6103          Call := Stmt;
6104
6105          Param := First (Parameter_Associations (Call));
6106          while Present (Param)
6107            and then not Is_RTE (Etype (Param), RE_Call_Modes)
6108          loop
6109             Next (Param);
6110          end loop;
6111
6112          pragma Assert (Present (Param));
6113          Rewrite (Param, New_Reference_To (RTE (RE_Asynchronous_Call), Loc));
6114          Analyze (Param);
6115
6116          --  Append an if statement to execute the abortable part
6117
6118          --  Generate:
6119          --    if Enqueued (Bnn) then
6120
6121          Append_To (Stmts,
6122            Make_Implicit_If_Statement (N,
6123              Condition => Make_Function_Call (Loc,
6124                Name => New_Reference_To (
6125                  RTE (RE_Enqueued), Loc),
6126                Parameter_Associations => New_List (
6127                  New_Reference_To (Cancel_Param, Loc))),
6128              Then_Statements => Astats));
6129
6130          Abortable_Block :=
6131            Make_Block_Statement (Loc,
6132              Identifier => New_Reference_To (Blk_Ent, Loc),
6133              Handled_Statement_Sequence =>
6134                Make_Handled_Sequence_Of_Statements (Loc,
6135                  Statements => Stmts),
6136              Has_Created_Identifier => True,
6137              Is_Asynchronous_Call_Block => True);
6138
6139          --  For the VM call Update_Exception instead of Abort_Undefer.
6140          --  See 4jexcept.ads for an explanation.
6141
6142          if VM_Target = No_VM then
6143             Target_Undefer := RE_Abort_Undefer;
6144          else
6145             Target_Undefer := RE_Update_Exception;
6146             Undefer_Args :=
6147               New_List (Make_Function_Call (Loc,
6148                           Name => New_Occurrence_Of
6149                                     (RTE (RE_Current_Target_Exception), Loc)));
6150          end if;
6151
6152          Stmts := New_List (
6153            Make_Block_Statement (Loc,
6154              Handled_Statement_Sequence =>
6155                Make_Handled_Sequence_Of_Statements (Loc,
6156                  Statements => New_List (
6157                    Make_Implicit_Label_Declaration (Loc,
6158                      Defining_Identifier => Blk_Ent,
6159                      Label_Construct     => Abortable_Block),
6160                    Abortable_Block),
6161
6162                --  exception
6163
6164                  Exception_Handlers => New_List (
6165                    Make_Implicit_Exception_Handler (Loc,
6166
6167                --  when Abort_Signal =>
6168                --     Abort_Undefer.all;
6169
6170                      Exception_Choices =>
6171                        New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6172                      Statements => New_List (
6173                        Make_Procedure_Call_Statement (Loc,
6174                          Name => New_Reference_To (
6175                            RTE (Target_Undefer), Loc),
6176                          Parameter_Associations => Undefer_Args)))))),
6177
6178          --  if not Cancelled (Bnn) then
6179          --     triggered statements
6180          --  end if;
6181
6182            Make_Implicit_If_Statement (N,
6183              Condition => Make_Op_Not (Loc,
6184                Right_Opnd =>
6185                  Make_Function_Call (Loc,
6186                    Name => New_Occurrence_Of (RTE (RE_Cancelled), Loc),
6187                    Parameter_Associations => New_List (
6188                      New_Occurrence_Of (Cancel_Param, Loc)))),
6189              Then_Statements => Tstats));
6190
6191       --  Asynchronous task entry call
6192
6193       else
6194          if No (Decls) then
6195             Decls := New_List;
6196          end if;
6197
6198          B := Make_Defining_Identifier (Loc, Name_uB);
6199
6200          --  Insert declaration of B in declarations of existing block
6201
6202          Prepend_To (Decls,
6203            Make_Object_Declaration (Loc,
6204              Defining_Identifier => B,
6205              Object_Definition => New_Reference_To (Standard_Boolean, Loc)));
6206
6207          Cancel_Param := Make_Defining_Identifier (Loc, Name_uC);
6208
6209          --  Insert declaration of C in declarations of existing block
6210
6211          Prepend_To (Decls,
6212            Make_Object_Declaration (Loc,
6213              Defining_Identifier => Cancel_Param,
6214              Object_Definition => New_Reference_To (Standard_Boolean, Loc)));
6215
6216          --  Remove and save the call to Call_Simple
6217
6218          Stmt := First (Stmts);
6219
6220          --  Skip assignments to temporaries created for in-out parameters.
6221          --  This makes unwarranted assumptions about the shape of the expanded
6222          --  tree for the call, and should be cleaned up ???
6223
6224          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6225             Next (Stmt);
6226          end loop;
6227
6228          Call := Stmt;
6229
6230          --  Create the inner block to protect the abortable part
6231
6232          Hdle :=  New_List (
6233            Make_Implicit_Exception_Handler (Loc,
6234              Exception_Choices =>
6235                New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6236              Statements =>
6237                New_List (
6238                  Make_Procedure_Call_Statement (Loc,
6239                    Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
6240
6241          Prepend_To (Astats,
6242            Make_Procedure_Call_Statement (Loc,
6243              Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)));
6244
6245          Abortable_Block :=
6246            Make_Block_Statement (Loc,
6247              Identifier => New_Reference_To (Blk_Ent, Loc),
6248              Handled_Statement_Sequence =>
6249                Make_Handled_Sequence_Of_Statements (Loc,
6250                  Statements => Astats),
6251              Has_Created_Identifier => True,
6252              Is_Asynchronous_Call_Block => True);
6253
6254          Insert_After (Call,
6255            Make_Block_Statement (Loc,
6256              Handled_Statement_Sequence =>
6257                Make_Handled_Sequence_Of_Statements (Loc,
6258                  Statements => New_List (
6259                    Make_Implicit_Label_Declaration (Loc,
6260                      Defining_Identifier =>
6261                        Blk_Ent,
6262                      Label_Construct =>
6263                        Abortable_Block),
6264                    Abortable_Block),
6265                  Exception_Handlers => Hdle)));
6266
6267          --  Create new call statement
6268
6269          Params := Parameter_Associations (Call);
6270
6271          Append_To (Params,
6272            New_Reference_To (RTE (RE_Asynchronous_Call), Loc));
6273          Append_To (Params,
6274            New_Reference_To (B, Loc));
6275
6276          Rewrite (Call,
6277            Make_Procedure_Call_Statement (Loc,
6278              Name =>
6279                New_Reference_To (RTE (RE_Task_Entry_Call), Loc),
6280              Parameter_Associations => Params));
6281
6282          --  Construct statement sequence for new block
6283
6284          Append_To (Stmts,
6285            Make_Implicit_If_Statement (N,
6286              Condition =>
6287                Make_Op_Not (Loc,
6288                  New_Reference_To (Cancel_Param, Loc)),
6289              Then_Statements => Tstats));
6290
6291          --  Protected the call against abort
6292
6293          Prepend_To (Stmts,
6294            Make_Procedure_Call_Statement (Loc,
6295              Name => New_Reference_To (RTE (RE_Abort_Defer), Loc),
6296              Parameter_Associations => Empty_List));
6297       end if;
6298
6299       Set_Entry_Cancel_Parameter (Blk_Ent, Cancel_Param);
6300
6301       --  The result is the new block
6302
6303       Rewrite (N_Orig,
6304         Make_Block_Statement (Loc,
6305           Declarations => Decls,
6306           Handled_Statement_Sequence =>
6307             Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6308
6309       Analyze (N_Orig);
6310    end Expand_N_Asynchronous_Select;
6311
6312    -------------------------------------
6313    -- Expand_N_Conditional_Entry_Call --
6314    -------------------------------------
6315
6316    --  The conditional task entry call is converted to a call to
6317    --  Task_Entry_Call:
6318
6319    --    declare
6320    --       B : Boolean;
6321    --       P : parms := (parm, parm, parm);
6322
6323    --    begin
6324    --       Task_Entry_Call
6325    --         (<acceptor-task>,   --  Acceptor
6326    --          <entry-index>,     --  E
6327    --          P'Address,         --  Uninterpreted_Data
6328    --          Conditional_Call,  --  Mode
6329    --          B);                --  Rendezvous_Successful
6330    --       parm := P.param;
6331    --       parm := P.param;
6332    --       ...
6333    --       if B then
6334    --          normal-statements
6335    --       else
6336    --          else-statements
6337    --       end if;
6338    --    end;
6339
6340    --  For a description of the use of P and the assignments after the call,
6341    --  see Expand_N_Entry_Call_Statement. Note that the entry call of the
6342    --  conditional entry call has already been expanded (by the Expand_N_Entry
6343    --  _Call_Statement procedure) as follows:
6344
6345    --    declare
6346    --       P : parms := (parm, parm, parm);
6347    --    begin
6348    --       ... info for in-out parameters
6349    --       Call_Simple (acceptor-task, entry-index, P'Address);
6350    --       parm := P.param;
6351    --       parm := P.param;
6352    --       ...
6353    --    end;
6354
6355    --  so the task at hand is to convert the latter expansion into the former
6356
6357    --  The conditional protected entry call is converted to a call to
6358    --  Protected_Entry_Call:
6359
6360    --    declare
6361    --       P : parms := (parm, parm, parm);
6362    --       Bnn : Communications_Block;
6363
6364    --    begin
6365    --       Protected_Entry_Call
6366    --         (po._object'Access,  --  Object
6367    --          <entry index>,      --  E
6368    --          P'Address,          --  Uninterpreted_Data
6369    --          Conditional_Call,   --  Mode
6370    --          Bnn);               --  Block
6371    --       parm := P.param;
6372    --       parm := P.param;
6373    --       ...
6374    --       if Cancelled (Bnn) then
6375    --          else-statements
6376    --       else
6377    --          normal-statements
6378    --       end if;
6379    --    end;
6380
6381    --  Ada 2005 (AI-345): A dispatching conditional entry call is converted
6382    --  into:
6383
6384    --    declare
6385    --       B : Boolean := False;
6386    --       C : Ada.Tags.Prim_Op_Kind;
6387    --       K : Ada.Tags.Tagged_Kind :=
6388    --             Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
6389    --       P : Parameters := (Param1 .. ParamN);
6390    --       S : Integer;
6391
6392    --    begin
6393    --       if K = Ada.Tags.TK_Limited_Tagged then
6394    --          <dispatching-call>;
6395    --          <triggering-statements>
6396
6397    --       else
6398    --          S :=
6399    --            Ada.Tags.Get_Offset_Index
6400    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
6401
6402    --          _Disp_Conditional_Select (<object>, S, P'Address, C, B);
6403
6404    --          if C = POK_Protected_Entry
6405    --            or else C = POK_Task_Entry
6406    --          then
6407    --             Param1 := P.Param1;
6408    --             ...
6409    --             ParamN := P.ParamN;
6410    --          end if;
6411
6412    --          if B then
6413    --             if C = POK_Procedure
6414    --               or else C = POK_Protected_Procedure
6415    --               or else C = POK_Task_Procedure
6416    --             then
6417    --                <dispatching-call>;
6418    --             end if;
6419
6420    --             <triggering-statements>
6421    --          else
6422    --             <else-statements>
6423    --          end if;
6424    --       end if;
6425    --    end;
6426
6427    procedure Expand_N_Conditional_Entry_Call (N : Node_Id) is
6428       Loc : constant Source_Ptr := Sloc (N);
6429       Alt : constant Node_Id    := Entry_Call_Alternative (N);
6430       Blk : Node_Id             := Entry_Call_Statement (Alt);
6431
6432       Actuals        : List_Id;
6433       Blk_Typ        : Entity_Id;
6434       Call           : Node_Id;
6435       Call_Ent       : Entity_Id;
6436       Conc_Typ_Stmts : List_Id;
6437       Decl           : Node_Id;
6438       Decls          : List_Id;
6439       Formals        : List_Id;
6440       Lim_Typ_Stmts  : List_Id;
6441       N_Stats        : List_Id;
6442       Obj            : Entity_Id;
6443       Param          : Node_Id;
6444       Params         : List_Id;
6445       Stmt           : Node_Id;
6446       Stmts          : List_Id;
6447       Transient_Blk  : Node_Id;
6448       Unpack         : List_Id;
6449
6450       B : Entity_Id;  --  Call status flag
6451       C : Entity_Id;  --  Call kind
6452       K : Entity_Id;  --  Tagged kind
6453       P : Entity_Id;  --  Parameter block
6454       S : Entity_Id;  --  Primitive operation slot
6455
6456    begin
6457       if Ada_Version >= Ada_05
6458         and then Nkind (Blk) = N_Procedure_Call_Statement
6459       then
6460          Extract_Dispatching_Call (Blk, Call_Ent, Obj, Actuals, Formals);
6461
6462          Decls := New_List;
6463          Stmts := New_List;
6464
6465          --  Call status flag processing, generate:
6466          --    B : Boolean := False;
6467
6468          B := Build_B (Loc, Decls);
6469
6470          --  Call kind processing, generate:
6471          --    C : Ada.Tags.Prim_Op_Kind;
6472
6473          C := Build_C (Loc, Decls);
6474
6475          --  Tagged kind processing, generate:
6476          --    K : Ada.Tags.Tagged_Kind :=
6477          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
6478
6479          K := Build_K (Loc, Decls, Obj);
6480
6481          --  Parameter block processing
6482
6483          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
6484          P       := Parameter_Block_Pack
6485                       (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
6486
6487          --  Dispatch table slot processing, generate:
6488          --    S : Integer;
6489
6490          S := Build_S (Loc, Decls);
6491
6492          --  Generate:
6493          --    S := Ada.Tags.Get_Offset_Index
6494          --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
6495
6496          Conc_Typ_Stmts :=
6497            New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
6498
6499          --  Generate:
6500          --    _Disp_Conditional_Select (<object>, S, P'Address, C, B);
6501
6502          Append_To (Conc_Typ_Stmts,
6503            Make_Procedure_Call_Statement (Loc,
6504              Name =>
6505                New_Reference_To (
6506                  Find_Prim_Op (Etype (Etype (Obj)),
6507                    Name_uDisp_Conditional_Select),
6508                  Loc),
6509              Parameter_Associations =>
6510                New_List (
6511                  New_Copy_Tree (Obj),            --  <object>
6512                  New_Reference_To (S, Loc),      --  S
6513                  Make_Attribute_Reference (Loc,  --  P'Address
6514                    Prefix =>
6515                      New_Reference_To (P, Loc),
6516                    Attribute_Name =>
6517                      Name_Address),
6518                  New_Reference_To (C, Loc),      --  C
6519                  New_Reference_To (B, Loc))));   --  B
6520
6521          --  Generate:
6522          --    if C = POK_Protected_Entry
6523          --      or else C = POK_Task_Entry
6524          --    then
6525          --       Param1 := P.Param1;
6526          --       ...
6527          --       ParamN := P.ParamN;
6528          --    end if;
6529
6530          Unpack := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
6531
6532          --  Generate the if statement only when the packed parameters need
6533          --  explicit assignments to their corresponding actuals.
6534
6535          if Present (Unpack) then
6536             Append_To (Conc_Typ_Stmts,
6537               Make_If_Statement (Loc,
6538
6539                 Condition =>
6540                   Make_Or_Else (Loc,
6541                     Left_Opnd =>
6542                       Make_Op_Eq (Loc,
6543                         Left_Opnd =>
6544                           New_Reference_To (C, Loc),
6545                         Right_Opnd =>
6546                           New_Reference_To (RTE (
6547                             RE_POK_Protected_Entry), Loc)),
6548                     Right_Opnd =>
6549                       Make_Op_Eq (Loc,
6550                         Left_Opnd =>
6551                           New_Reference_To (C, Loc),
6552                         Right_Opnd =>
6553                           New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
6554
6555                  Then_Statements =>
6556                    Unpack));
6557          end if;
6558
6559          --  Generate:
6560          --    if B then
6561          --       if C = POK_Procedure
6562          --         or else C = POK_Protected_Procedure
6563          --         or else C = POK_Task_Procedure
6564          --       then
6565          --          <dispatching-call>
6566          --       end if;
6567          --       <normal-statements>
6568          --    else
6569          --       <else-statements>
6570          --    end if;
6571
6572          N_Stats := New_Copy_List_Tree (Statements (Alt));
6573
6574          Prepend_To (N_Stats,
6575            Make_If_Statement (Loc,
6576              Condition =>
6577                Make_Or_Else (Loc,
6578                  Left_Opnd =>
6579                    Make_Op_Eq (Loc,
6580                      Left_Opnd =>
6581                        New_Reference_To (C, Loc),
6582                      Right_Opnd =>
6583                        New_Reference_To (RTE (RE_POK_Procedure), Loc)),
6584
6585                  Right_Opnd =>
6586                    Make_Or_Else (Loc,
6587                      Left_Opnd =>
6588                        Make_Op_Eq (Loc,
6589                          Left_Opnd =>
6590                            New_Reference_To (C, Loc),
6591                          Right_Opnd =>
6592                            New_Reference_To (RTE (
6593                              RE_POK_Protected_Procedure), Loc)),
6594
6595                      Right_Opnd =>
6596                        Make_Op_Eq (Loc,
6597                          Left_Opnd =>
6598                            New_Reference_To (C, Loc),
6599                          Right_Opnd =>
6600                            New_Reference_To (RTE (
6601                              RE_POK_Task_Procedure), Loc)))),
6602
6603              Then_Statements =>
6604                New_List (Blk)));
6605
6606          Append_To (Conc_Typ_Stmts,
6607            Make_If_Statement (Loc,
6608              Condition => New_Reference_To (B, Loc),
6609              Then_Statements => N_Stats,
6610              Else_Statements => Else_Statements (N)));
6611
6612          --  Generate:
6613          --    <dispatching-call>;
6614          --    <triggering-statements>
6615
6616          Lim_Typ_Stmts := New_Copy_List_Tree (Statements (Alt));
6617          Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (Blk));
6618
6619          --  Generate:
6620          --    if K = Ada.Tags.TK_Limited_Tagged then
6621          --       Lim_Typ_Stmts
6622          --    else
6623          --       Conc_Typ_Stmts
6624          --    end if;
6625
6626          Append_To (Stmts,
6627            Make_If_Statement (Loc,
6628              Condition =>
6629                Make_Op_Eq (Loc,
6630                  Left_Opnd =>
6631                    New_Reference_To (K, Loc),
6632                  Right_Opnd =>
6633                    New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
6634
6635              Then_Statements =>
6636                Lim_Typ_Stmts,
6637
6638              Else_Statements =>
6639                Conc_Typ_Stmts));
6640
6641          Rewrite (N,
6642            Make_Block_Statement (Loc,
6643              Declarations =>
6644                Decls,
6645              Handled_Statement_Sequence =>
6646                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6647
6648       --  As described above, The entry alternative is transformed into a
6649       --  block that contains the gnulli call, and possibly assignment
6650       --  statements for in-out parameters. The gnulli call may itself be
6651       --  rewritten into a transient block if some unconstrained parameters
6652       --  require it. We need to retrieve the call to complete its parameter
6653       --  list.
6654
6655       else
6656          Transient_Blk :=
6657            First_Real_Statement (Handled_Statement_Sequence (Blk));
6658
6659          if Present (Transient_Blk)
6660            and then Nkind (Transient_Blk) = N_Block_Statement
6661          then
6662             Blk := Transient_Blk;
6663          end if;
6664
6665          Stmts := Statements (Handled_Statement_Sequence (Blk));
6666          Stmt  := First (Stmts);
6667          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6668             Next (Stmt);
6669          end loop;
6670
6671          Call   := Stmt;
6672          Params := Parameter_Associations (Call);
6673
6674          if Is_RTE (Entity (Name (Call)), RE_Protected_Entry_Call) then
6675
6676             --  Substitute Conditional_Entry_Call for Simple_Call parameter
6677
6678             Param := First (Params);
6679             while Present (Param)
6680               and then not Is_RTE (Etype (Param), RE_Call_Modes)
6681             loop
6682                Next (Param);
6683             end loop;
6684
6685             pragma Assert (Present (Param));
6686             Rewrite (Param, New_Reference_To (RTE (RE_Conditional_Call), Loc));
6687
6688             Analyze (Param);
6689
6690             --  Find the Communication_Block parameter for the call to the
6691             --  Cancelled function.
6692
6693             Decl := First (Declarations (Blk));
6694             while Present (Decl)
6695               and then not Is_RTE (Etype (Object_Definition (Decl)),
6696                              RE_Communication_Block)
6697             loop
6698                Next (Decl);
6699             end loop;
6700
6701             --  Add an if statement to execute the else part if the call
6702             --  does not succeed (as indicated by the Cancelled predicate).
6703
6704             Append_To (Stmts,
6705               Make_Implicit_If_Statement (N,
6706                 Condition => Make_Function_Call (Loc,
6707                   Name => New_Reference_To (RTE (RE_Cancelled), Loc),
6708                   Parameter_Associations => New_List (
6709                     New_Reference_To (Defining_Identifier (Decl), Loc))),
6710                 Then_Statements => Else_Statements (N),
6711                 Else_Statements => Statements (Alt)));
6712
6713          else
6714             B := Make_Defining_Identifier (Loc, Name_uB);
6715
6716             --  Insert declaration of B in declarations of existing block
6717
6718             if No (Declarations (Blk)) then
6719                Set_Declarations (Blk, New_List);
6720             end if;
6721
6722             Prepend_To (Declarations (Blk),
6723               Make_Object_Declaration (Loc,
6724                 Defining_Identifier => B,
6725                 Object_Definition =>
6726                   New_Reference_To (Standard_Boolean, Loc)));
6727
6728             --  Create new call statement
6729
6730             Append_To (Params,
6731               New_Reference_To (RTE (RE_Conditional_Call), Loc));
6732             Append_To (Params, New_Reference_To (B, Loc));
6733
6734             Rewrite (Call,
6735               Make_Procedure_Call_Statement (Loc,
6736                 Name => New_Reference_To (RTE (RE_Task_Entry_Call), Loc),
6737                 Parameter_Associations => Params));
6738
6739             --  Construct statement sequence for new block
6740
6741             Append_To (Stmts,
6742               Make_Implicit_If_Statement (N,
6743                 Condition => New_Reference_To (B, Loc),
6744                 Then_Statements => Statements (Alt),
6745                 Else_Statements => Else_Statements (N)));
6746          end if;
6747
6748          --  The result is the new block
6749
6750          Rewrite (N,
6751            Make_Block_Statement (Loc,
6752              Declarations => Declarations (Blk),
6753              Handled_Statement_Sequence =>
6754                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6755       end if;
6756
6757       Analyze (N);
6758    end Expand_N_Conditional_Entry_Call;
6759
6760    ---------------------------------------
6761    -- Expand_N_Delay_Relative_Statement --
6762    ---------------------------------------
6763
6764    --  Delay statement is implemented as a procedure call to Delay_For
6765    --  defined in Ada.Calendar.Delays in order to reduce the overhead of
6766    --  simple delays imposed by the use of Protected Objects.
6767
6768    procedure Expand_N_Delay_Relative_Statement (N : Node_Id) is
6769       Loc : constant Source_Ptr := Sloc (N);
6770    begin
6771       Rewrite (N,
6772         Make_Procedure_Call_Statement (Loc,
6773           Name => New_Reference_To (RTE (RO_CA_Delay_For), Loc),
6774           Parameter_Associations => New_List (Expression (N))));
6775       Analyze (N);
6776    end Expand_N_Delay_Relative_Statement;
6777
6778    ------------------------------------
6779    -- Expand_N_Delay_Until_Statement --
6780    ------------------------------------
6781
6782    --  Delay Until statement is implemented as a procedure call to
6783    --  Delay_Until defined in Ada.Calendar.Delays and Ada.Real_Time.Delays.
6784
6785    procedure Expand_N_Delay_Until_Statement (N : Node_Id) is
6786       Loc : constant Source_Ptr := Sloc (N);
6787       Typ : Entity_Id;
6788
6789    begin
6790       if Is_RTE (Base_Type (Etype (Expression (N))), RO_CA_Time) then
6791          Typ := RTE (RO_CA_Delay_Until);
6792       else
6793          Typ := RTE (RO_RT_Delay_Until);
6794       end if;
6795
6796       Rewrite (N,
6797         Make_Procedure_Call_Statement (Loc,
6798           Name => New_Reference_To (Typ, Loc),
6799           Parameter_Associations => New_List (Expression (N))));
6800
6801       Analyze (N);
6802    end Expand_N_Delay_Until_Statement;
6803
6804    -------------------------
6805    -- Expand_N_Entry_Body --
6806    -------------------------
6807
6808    procedure Expand_N_Entry_Body (N : Node_Id) is
6809    begin
6810       --  Associate discriminals with the next protected operation body to be
6811       --  expanded.
6812
6813       if Present (Next_Protected_Operation (N)) then
6814          Set_Discriminals (Parent (Current_Scope));
6815       end if;
6816    end Expand_N_Entry_Body;
6817
6818    -----------------------------------
6819    -- Expand_N_Entry_Call_Statement --
6820    -----------------------------------
6821
6822    --  An entry call is expanded into GNARLI calls to implement a simple entry
6823    --  call (see Build_Simple_Entry_Call).
6824
6825    procedure Expand_N_Entry_Call_Statement (N : Node_Id) is
6826       Concval : Node_Id;
6827       Ename   : Node_Id;
6828       Index   : Node_Id;
6829
6830    begin
6831       if No_Run_Time_Mode then
6832          Error_Msg_CRT ("entry call", N);
6833          return;
6834       end if;
6835
6836       --  If this entry call is part of an asynchronous select, don't expand it
6837       --  here; it will be expanded with the select statement. Don't expand
6838       --  timed entry calls either, as they are translated into asynchronous
6839       --  entry calls.
6840
6841       --  ??? This whole approach is questionable; it may be better to go back
6842       --  to allowing the expansion to take place and then attempting to fix it
6843       --  up in Expand_N_Asynchronous_Select. The tricky part is figuring out
6844       --  whether the expanded call is on a task or protected entry.
6845
6846       if (Nkind (Parent (N)) /= N_Triggering_Alternative
6847            or else N /= Triggering_Statement (Parent (N)))
6848         and then (Nkind (Parent (N)) /= N_Entry_Call_Alternative
6849                    or else N /= Entry_Call_Statement (Parent (N))
6850                    or else Nkind (Parent (Parent (N))) /= N_Timed_Entry_Call)
6851       then
6852          Extract_Entry (N, Concval, Ename, Index);
6853          Build_Simple_Entry_Call (N, Concval, Ename, Index);
6854       end if;
6855    end Expand_N_Entry_Call_Statement;
6856
6857    --------------------------------
6858    -- Expand_N_Entry_Declaration --
6859    --------------------------------
6860
6861    --  If there are parameters, then first, each of the formals is marked by
6862    --  setting Is_Entry_Formal. Next a record type is built which is used to
6863    --  hold the parameter values. The name of this record type is entryP where
6864    --  entry is the name of the entry, with an additional corresponding access
6865    --  type called entryPA. The record type has matching components for each
6866    --  formal (the component names are the same as the formal names). For
6867    --  elementary types, the component type matches the formal type. For
6868    --  composite types, an access type is declared (with the name formalA)
6869    --  which designates the formal type, and the type of the component is this
6870    --  access type. Finally the Entry_Component of each formal is set to
6871    --  reference the corresponding record component.
6872
6873    procedure Expand_N_Entry_Declaration (N : Node_Id) is
6874       Loc        : constant Source_Ptr := Sloc (N);
6875       Entry_Ent  : constant Entity_Id  := Defining_Identifier (N);
6876       Components : List_Id;
6877       Formal     : Node_Id;
6878       Ftype      : Entity_Id;
6879       Last_Decl  : Node_Id;
6880       Component  : Entity_Id;
6881       Ctype      : Entity_Id;
6882       Decl       : Node_Id;
6883       Rec_Ent    : Entity_Id;
6884       Acc_Ent    : Entity_Id;
6885
6886    begin
6887       Formal := First_Formal (Entry_Ent);
6888       Last_Decl := N;
6889
6890       --  Most processing is done only if parameters are present
6891
6892       if Present (Formal) then
6893          Components := New_List;
6894
6895          --  Loop through formals
6896
6897          while Present (Formal) loop
6898             Set_Is_Entry_Formal (Formal);
6899             Component :=
6900               Make_Defining_Identifier (Sloc (Formal), Chars (Formal));
6901             Set_Entry_Component (Formal, Component);
6902             Set_Entry_Formal (Component, Formal);
6903             Ftype := Etype (Formal);
6904
6905             --  Declare new access type and then append
6906
6907             Ctype :=
6908               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
6909
6910             Decl :=
6911               Make_Full_Type_Declaration (Loc,
6912                 Defining_Identifier => Ctype,
6913                 Type_Definition     =>
6914                   Make_Access_To_Object_Definition (Loc,
6915                     All_Present        => True,
6916                     Constant_Present   => Ekind (Formal) = E_In_Parameter,
6917                     Subtype_Indication => New_Reference_To (Ftype, Loc)));
6918
6919             Insert_After (Last_Decl, Decl);
6920             Last_Decl := Decl;
6921
6922             Append_To (Components,
6923               Make_Component_Declaration (Loc,
6924                 Defining_Identifier => Component,
6925                 Component_Definition =>
6926                   Make_Component_Definition (Loc,
6927                     Aliased_Present    => False,
6928                     Subtype_Indication => New_Reference_To (Ctype, Loc))));
6929
6930             Next_Formal_With_Extras (Formal);
6931          end loop;
6932
6933          --  Create the Entry_Parameter_Record declaration
6934
6935          Rec_Ent :=
6936            Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
6937
6938          Decl :=
6939            Make_Full_Type_Declaration (Loc,
6940              Defining_Identifier => Rec_Ent,
6941              Type_Definition     =>
6942                Make_Record_Definition (Loc,
6943                  Component_List =>
6944                    Make_Component_List (Loc,
6945                      Component_Items => Components)));
6946
6947          Insert_After (Last_Decl, Decl);
6948          Last_Decl := Decl;
6949
6950          --  Construct and link in the corresponding access type
6951
6952          Acc_Ent :=
6953            Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
6954
6955          Set_Entry_Parameters_Type (Entry_Ent, Acc_Ent);
6956
6957          Decl :=
6958            Make_Full_Type_Declaration (Loc,
6959              Defining_Identifier => Acc_Ent,
6960              Type_Definition     =>
6961                Make_Access_To_Object_Definition (Loc,
6962                  All_Present        => True,
6963                  Subtype_Indication => New_Reference_To (Rec_Ent, Loc)));
6964
6965          Insert_After (Last_Decl, Decl);
6966          Last_Decl := Decl;
6967       end if;
6968    end Expand_N_Entry_Declaration;
6969
6970    -----------------------------
6971    -- Expand_N_Protected_Body --
6972    -----------------------------
6973
6974    --  Protected bodies are expanded to the completion of the subprograms
6975    --  created for the corresponding protected type. These are a protected and
6976    --  unprotected version of each protected subprogram in the object, a
6977    --  function to calculate each entry barrier, and a procedure to execute the
6978    --  sequence of statements of each protected entry body. For example, for
6979    --  protected type ptype:
6980
6981    --  function entB
6982    --    (O : System.Address;
6983    --     E : Protected_Entry_Index)
6984    --     return Boolean
6985    --  is
6986    --     <discriminant renamings>
6987    --     <private object renamings>
6988    --  begin
6989    --     return <barrier expression>;
6990    --  end entB;
6991
6992    --  procedure pprocN (_object : in out poV;...) is
6993    --     <discriminant renamings>
6994    --     <private object renamings>
6995    --  begin
6996    --     <sequence of statements>
6997    --  end pprocN;
6998
6999    --  procedure pprocP (_object : in out poV;...) is
7000    --     procedure _clean is
7001    --       Pn : Boolean;
7002    --     begin
7003    --       ptypeS (_object, Pn);
7004    --       Unlock (_object._object'Access);
7005    --       Abort_Undefer.all;
7006    --     end _clean;
7007
7008    --  begin
7009    --     Abort_Defer.all;
7010    --     Lock (_object._object'Access);
7011    --     pprocN (_object;...);
7012    --  at end
7013    --     _clean;
7014    --  end pproc;
7015
7016    --  function pfuncN (_object : poV;...) return Return_Type is
7017    --     <discriminant renamings>
7018    --     <private object renamings>
7019    --  begin
7020    --     <sequence of statements>
7021    --  end pfuncN;
7022
7023    --  function pfuncP (_object : poV) return Return_Type is
7024    --     procedure _clean is
7025    --     begin
7026    --        Unlock (_object._object'Access);
7027    --        Abort_Undefer.all;
7028    --     end _clean;
7029
7030    --  begin
7031    --     Abort_Defer.all;
7032    --     Lock (_object._object'Access);
7033    --     return pfuncN (_object);
7034
7035    --  at end
7036    --     _clean;
7037    --  end pfunc;
7038
7039    --  procedure entE
7040    --    (O : System.Address;
7041    --     P : System.Address;
7042    --     E : Protected_Entry_Index)
7043    --  is
7044    --     <discriminant renamings>
7045    --     <private object renamings>
7046    --     type poVP is access poV;
7047    --     _Object : ptVP := ptVP!(O);
7048
7049    --  begin
7050    --     begin
7051    --        <statement sequence>
7052    --        Complete_Entry_Body (_Object._Object);
7053    --     exception
7054    --        when all others =>
7055    --           Exceptional_Complete_Entry_Body (
7056    --             _Object._Object, Get_GNAT_Exception);
7057    --     end;
7058    --  end entE;
7059
7060    --  The type poV is the record created for the protected type to hold
7061    --  the state of the protected object.
7062
7063    procedure Expand_N_Protected_Body (N : Node_Id) is
7064       Loc          : constant Source_Ptr := Sloc (N);
7065       Pid          : constant Entity_Id  := Corresponding_Spec (N);
7066
7067       Current_Node : Node_Id;
7068       Disp_Op_Body : Node_Id;
7069       New_Op_Body  : Node_Id;
7070       Num_Entries  : Natural := 0;
7071       Op_Body      : Node_Id;
7072       Op_Decl      : Node_Id;
7073       Op_Id        : Entity_Id;
7074
7075       Chain        : Entity_Id := Empty;
7076       --  Finalization chain that may be attached to new body
7077
7078       function Build_Dispatching_Subprogram_Body
7079         (N        : Node_Id;
7080          Pid      : Node_Id;
7081          Prot_Bod : Node_Id) return Node_Id;
7082       --  Build a dispatching version of the protected subprogram body. The
7083       --  newly generated subprogram contains a call to the original protected
7084       --  body. The following code is generated:
7085       --
7086       --  function <protected-function-name> (Param1 .. ParamN) return
7087       --    <return-type> is
7088       --  begin
7089       --     return <protected-function-name>P (Param1 .. ParamN);
7090       --  end <protected-function-name>;
7091       --
7092       --  or
7093       --
7094       --  procedure <protected-procedure-name> (Param1 .. ParamN) is
7095       --  begin
7096       --     <protected-procedure-name>P (Param1 .. ParamN);
7097       --  end <protected-procedure-name>
7098
7099       ---------------------------------------
7100       -- Build_Dispatching_Subprogram_Body --
7101       ---------------------------------------
7102
7103       function Build_Dispatching_Subprogram_Body
7104         (N        : Node_Id;
7105          Pid      : Node_Id;
7106          Prot_Bod : Node_Id) return Node_Id
7107       is
7108          Loc     : constant Source_Ptr := Sloc (N);
7109          Actuals : List_Id;
7110          Formal  : Node_Id;
7111          Spec    : Node_Id;
7112          Stmts   : List_Id;
7113
7114       begin
7115          --  Generate a specification without a letter suffix in order to
7116          --  override an interface function or procedure.
7117
7118          Spec :=
7119            Build_Protected_Sub_Specification (N, Pid, Dispatching_Mode);
7120
7121          --  The formal parameters become the actuals of the protected
7122          --  function or procedure call.
7123
7124          Actuals := New_List;
7125          Formal  := First (Parameter_Specifications (Spec));
7126          while Present (Formal) loop
7127             Append_To (Actuals,
7128               Make_Identifier (Loc, Chars (Defining_Identifier (Formal))));
7129
7130             Next (Formal);
7131          end loop;
7132
7133          if Nkind (Spec) = N_Procedure_Specification then
7134             Stmts :=
7135               New_List (
7136                 Make_Procedure_Call_Statement (Loc,
7137                   Name =>
7138                     New_Reference_To (Corresponding_Spec (Prot_Bod), Loc),
7139                   Parameter_Associations => Actuals));
7140          else
7141             pragma Assert (Nkind (Spec) = N_Function_Specification);
7142
7143             Stmts :=
7144               New_List (
7145                 Make_Simple_Return_Statement (Loc,
7146                   Expression =>
7147                     Make_Function_Call (Loc,
7148                       Name =>
7149                         New_Reference_To (Corresponding_Spec (Prot_Bod), Loc),
7150                       Parameter_Associations => Actuals)));
7151          end if;
7152
7153          return
7154            Make_Subprogram_Body (Loc,
7155              Declarations  => Empty_List,
7156              Specification => Spec,
7157              Handled_Statement_Sequence =>
7158                Make_Handled_Sequence_Of_Statements (Loc, Stmts));
7159       end Build_Dispatching_Subprogram_Body;
7160
7161    --  Start of processing for Expand_N_Protected_Body
7162
7163    begin
7164       if No_Run_Time_Mode then
7165          Error_Msg_CRT ("protected body", N);
7166          return;
7167       end if;
7168
7169       --  This is the proper body corresponding to a stub. The declarations
7170       --  must be inserted at the point of the stub, which in turn is in the
7171       --  declarative part of the parent unit.
7172
7173       if Nkind (Parent (N)) = N_Subunit then
7174          Current_Node := Corresponding_Stub (Parent (N));
7175       else
7176          Current_Node := N;
7177       end if;
7178
7179       Op_Body := First (Declarations (N));
7180
7181       --  The protected body is replaced with the bodies of its
7182       --  protected operations, and the declarations for internal objects
7183       --  that may have been created for entry family bounds.
7184
7185       Rewrite (N, Make_Null_Statement (Sloc (N)));
7186       Analyze (N);
7187
7188       while Present (Op_Body) loop
7189          case Nkind (Op_Body) is
7190             when N_Subprogram_Declaration =>
7191                null;
7192
7193             when N_Subprogram_Body =>
7194
7195                --  Exclude functions created to analyze defaults
7196
7197                if not Is_Eliminated (Defining_Entity (Op_Body))
7198                  and then not Is_Eliminated (Corresponding_Spec (Op_Body))
7199                then
7200                   New_Op_Body :=
7201                     Build_Unprotected_Subprogram_Body (Op_Body, Pid);
7202
7203                   --  Propagate the finalization chain to the new body.
7204                   --  In the unlikely event that the subprogram contains a
7205                   --  declaration or allocator for an object that requires
7206                   --  finalization, the corresponding chain is created when
7207                   --  analyzing the body, and attached to its entity. This
7208                   --  entity is not further elaborated, and so the chain
7209                   --  properly belongs to the newly created subprogram body.
7210
7211                   Chain :=
7212                     Finalization_Chain_Entity (Defining_Entity (Op_Body));
7213
7214                   if Present (Chain) then
7215                      Set_Finalization_Chain_Entity
7216                        (Protected_Body_Subprogram
7217                          (Corresponding_Spec (Op_Body)), Chain);
7218                      Set_Analyzed
7219                          (Handled_Statement_Sequence (New_Op_Body), False);
7220                   end if;
7221
7222                   Insert_After (Current_Node, New_Op_Body);
7223                   Current_Node := New_Op_Body;
7224                   Analyze (New_Op_Body);
7225
7226                   --  Build the corresponding protected operation. It may
7227                   --  appear that this is needed only if this is a visible
7228                   --  operation of the type, or if it is an interrupt handler,
7229                   --  and this was the strategy used previously in GNAT.
7230                   --  However, the operation may be exported through a
7231                   --  'Access to an external caller. This is the common idiom
7232                   --  in code that uses the Ada 2005 Timing_Events package
7233                   --  As a result we need to produce the protected body for
7234                   --  both visible and private operations.
7235
7236                   if Present (Corresponding_Spec (Op_Body)) then
7237                      Op_Decl :=
7238                        Unit_Declaration_Node (Corresponding_Spec (Op_Body));
7239
7240                      if Nkind (Parent (Op_Decl)) =
7241                           N_Protected_Definition
7242                      then
7243                         New_Op_Body :=
7244                           Build_Protected_Subprogram_Body (
7245                             Op_Body, Pid, Specification (New_Op_Body));
7246
7247                         Insert_After (Current_Node, New_Op_Body);
7248                         Analyze (New_Op_Body);
7249
7250                         Current_Node := New_Op_Body;
7251
7252                         --  Generate an overriding primitive operation body for
7253                         --  this subprogram if the protected type implements
7254                         --  an interface.
7255
7256                         if Ada_Version >= Ada_05
7257                           and then Present (Interfaces (
7258                                      Corresponding_Record_Type (Pid)))
7259                         then
7260                            Disp_Op_Body :=
7261                              Build_Dispatching_Subprogram_Body (
7262                                Op_Body, Pid, New_Op_Body);
7263
7264                            Insert_After (Current_Node, Disp_Op_Body);
7265                            Analyze (Disp_Op_Body);
7266
7267                            Current_Node := Disp_Op_Body;
7268                         end if;
7269                      end if;
7270                   end if;
7271                end if;
7272
7273             when N_Entry_Body =>
7274                Op_Id := Defining_Identifier (Op_Body);
7275                Num_Entries := Num_Entries + 1;
7276
7277                New_Op_Body := Build_Protected_Entry (Op_Body, Op_Id, Pid);
7278
7279                Insert_After (Current_Node, New_Op_Body);
7280                Current_Node := New_Op_Body;
7281                Analyze (New_Op_Body);
7282
7283             when N_Implicit_Label_Declaration =>
7284                null;
7285
7286             when N_Itype_Reference =>
7287                Insert_After (Current_Node, New_Copy (Op_Body));
7288
7289             when N_Freeze_Entity =>
7290                New_Op_Body := New_Copy (Op_Body);
7291
7292                if Present (Entity (Op_Body))
7293                  and then Freeze_Node (Entity (Op_Body)) = Op_Body
7294                then
7295                   Set_Freeze_Node (Entity (Op_Body), New_Op_Body);
7296                end if;
7297
7298                Insert_After (Current_Node, New_Op_Body);
7299                Current_Node := New_Op_Body;
7300                Analyze (New_Op_Body);
7301
7302             when N_Pragma =>
7303                New_Op_Body := New_Copy (Op_Body);
7304                Insert_After (Current_Node, New_Op_Body);
7305                Current_Node := New_Op_Body;
7306                Analyze (New_Op_Body);
7307
7308             when N_Object_Declaration =>
7309                pragma Assert (not Comes_From_Source (Op_Body));
7310                New_Op_Body := New_Copy (Op_Body);
7311                Insert_After (Current_Node, New_Op_Body);
7312                Current_Node := New_Op_Body;
7313                Analyze (New_Op_Body);
7314
7315             when others =>
7316                raise Program_Error;
7317
7318          end case;
7319
7320          Next (Op_Body);
7321       end loop;
7322
7323       --  Finally, create the body of the function that maps an entry index
7324       --  into the corresponding body index, except when there is no entry,
7325       --  or in a ravenscar-like profile.
7326
7327       if Corresponding_Runtime_Package (Pid) =
7328            System_Tasking_Protected_Objects_Entries
7329       then
7330          New_Op_Body := Build_Find_Body_Index (Pid);
7331          Insert_After (Current_Node, New_Op_Body);
7332          Current_Node := New_Op_Body;
7333          Analyze (New_Op_Body);
7334       end if;
7335
7336       --  Ada 2005 (AI-345): Construct the primitive wrapper bodies after the
7337       --  protected body. At this point all wrapper specs have been created,
7338       --  frozen and included in the dispatch table for the protected type.
7339
7340       if Ada_Version >= Ada_05 then
7341          Build_Wrapper_Bodies (Loc, Pid, Current_Node);
7342       end if;
7343    end Expand_N_Protected_Body;
7344
7345    -----------------------------------------
7346    -- Expand_N_Protected_Type_Declaration --
7347    -----------------------------------------
7348
7349    --  First we create a corresponding record type declaration used to
7350    --  represent values of this protected type.
7351    --  The general form of this type declaration is
7352
7353    --    type poV (discriminants) is record
7354    --      _Object       : aliased <kind>Protection
7355    --         [(<entry count> [, <handler count>])];
7356    --      [entry_family  : array (bounds) of Void;]
7357    --      <private data fields>
7358    --    end record;
7359
7360    --  The discriminants are present only if the corresponding protected type
7361    --  has discriminants, and they exactly mirror the protected type
7362    --  discriminants. The private data fields similarly mirror the private
7363    --  declarations of the protected type.
7364
7365    --  The Object field is always present. It contains RTS specific data used
7366    --  to control the protected object. It is declared as Aliased so that it
7367    --  can be passed as a pointer to the RTS. This allows the protected record
7368    --  to be referenced within RTS data structures. An appropriate Protection
7369    --  type and discriminant are generated.
7370
7371    --  The Service field is present for protected objects with entries. It
7372    --  contains sufficient information to allow the entry service procedure for
7373    --  this object to be called when the object is not known till runtime.
7374
7375    --  One entry_family component is present for each entry family in the
7376    --  task definition (see Expand_N_Task_Type_Declaration).
7377
7378    --  When a protected object is declared, an instance of the protected type
7379    --  value record is created. The elaboration of this declaration creates the
7380    --  correct bounds for the entry families, and also evaluates the priority
7381    --  expression if needed. The initialization routine for the protected type
7382    --  itself then calls Initialize_Protection with appropriate parameters to
7383    --  initialize the value of the Task_Id field. Install_Handlers may be also
7384    --  called if a pragma Attach_Handler applies.
7385
7386    --  Note: this record is passed to the subprograms created by the expansion
7387    --  of protected subprograms and entries. It is an in parameter to protected
7388    --  functions and an in out parameter to procedures and entry bodies. The
7389    --  Entity_Id for this created record type is placed in the
7390    --  Corresponding_Record_Type field of the associated protected type entity.
7391
7392    --  Next we create a procedure specifications for protected subprograms and
7393    --  entry bodies. For each protected subprograms two subprograms are
7394    --  created, an unprotected and a protected version. The unprotected version
7395    --  is called from within other operations of the same protected object.
7396
7397    --  We also build the call to register the procedure if a pragma
7398    --  Interrupt_Handler applies.
7399
7400    --  A single subprogram is created to service all entry bodies; it has an
7401    --  additional boolean out parameter indicating that the previous entry call
7402    --  made by the current task was serviced immediately, i.e. not by proxy.
7403    --  The O parameter contains a pointer to a record object of the type
7404    --  described above. An untyped interface is used here to allow this
7405    --  procedure to be called in places where the type of the object to be
7406    --  serviced is not known. This must be done, for example, when a call that
7407    --  may have been requeued is cancelled; the corresponding object must be
7408    --  serviced, but which object that is not known till runtime.
7409
7410    --  procedure ptypeS
7411    --    (O : System.Address; P : out Boolean);
7412    --  procedure pprocN (_object : in out poV);
7413    --  procedure pproc (_object : in out poV);
7414    --  function pfuncN (_object : poV);
7415    --  function pfunc (_object : poV);
7416    --  ...
7417
7418    --  Note that this must come after the record type declaration, since
7419    --  the specs refer to this type.
7420
7421    procedure Expand_N_Protected_Type_Declaration (N : Node_Id) is
7422       Loc      : constant Source_Ptr := Sloc (N);
7423       Prot_Typ : constant Entity_Id  := Defining_Identifier (N);
7424
7425       Pdef     : constant Node_Id    := Protected_Definition (N);
7426       --  This contains two lists; one for visible and one for private decls
7427
7428       Rec_Decl     : Node_Id;
7429       Cdecls       : List_Id;
7430       Discr_Map    : constant Elist_Id := New_Elmt_List;
7431       Priv         : Node_Id;
7432       New_Priv     : Node_Id;
7433       Comp         : Node_Id;
7434       Comp_Id      : Entity_Id;
7435       Sub          : Node_Id;
7436       Current_Node : Node_Id := N;
7437       Bdef         : Entity_Id := Empty; -- avoid uninit warning
7438       Edef         : Entity_Id := Empty; -- avoid uninit warning
7439       Entries_Aggr : Node_Id;
7440       Body_Id      : Entity_Id;
7441       Body_Arr     : Node_Id;
7442       E_Count      : Int;
7443       Object_Comp  : Node_Id;
7444
7445       procedure Register_Handler;
7446       --  For a protected operation that is an interrupt handler, add the
7447       --  freeze action that will register it as such.
7448
7449       ----------------------
7450       -- Register_Handler --
7451       ----------------------
7452
7453       procedure Register_Handler is
7454
7455          --  All semantic checks already done in Sem_Prag
7456
7457          Prot_Proc    : constant Entity_Id :=
7458                        Defining_Unit_Name
7459                          (Specification (Current_Node));
7460
7461          Proc_Address : constant Node_Id :=
7462                           Make_Attribute_Reference (Loc,
7463                           Prefix => New_Reference_To (Prot_Proc, Loc),
7464                           Attribute_Name => Name_Address);
7465
7466          RTS_Call     : constant Entity_Id :=
7467                           Make_Procedure_Call_Statement (Loc,
7468                             Name =>
7469                               New_Reference_To (
7470                                 RTE (RE_Register_Interrupt_Handler), Loc),
7471                             Parameter_Associations =>
7472                               New_List (Proc_Address));
7473       begin
7474          Append_Freeze_Action (Prot_Proc, RTS_Call);
7475       end Register_Handler;
7476
7477    --  Start of processing for Expand_N_Protected_Type_Declaration
7478
7479    begin
7480       if Present (Corresponding_Record_Type (Prot_Typ)) then
7481          return;
7482       else
7483          Rec_Decl := Build_Corresponding_Record (N, Prot_Typ, Loc);
7484       end if;
7485
7486       Cdecls := Component_Items (Component_List (Type_Definition (Rec_Decl)));
7487
7488       --  Ada 2005 (AI-345): Propagate the attribute that contains the list
7489       --  of implemented interfaces.
7490
7491       Set_Interface_List (Type_Definition (Rec_Decl), Interface_List (N));
7492
7493       Qualify_Entity_Names (N);
7494
7495       --  If the type has discriminants, their occurrences in the declaration
7496       --  have been replaced by the corresponding discriminals. For components
7497       --  that are constrained by discriminants, their homologues in the
7498       --  corresponding record type must refer to the discriminants of that
7499       --  record, so we must apply a new renaming to subtypes_indications:
7500
7501       --     protected discriminant => discriminal => record discriminant
7502
7503       --  This replacement is not applied to default expressions, for which
7504       --  the discriminal is correct.
7505
7506       if Has_Discriminants (Prot_Typ) then
7507          declare
7508             Disc : Entity_Id;
7509             Decl : Node_Id;
7510
7511          begin
7512             Disc := First_Discriminant (Prot_Typ);
7513             Decl := First (Discriminant_Specifications (Rec_Decl));
7514             while Present (Disc) loop
7515                Append_Elmt (Discriminal (Disc), Discr_Map);
7516                Append_Elmt (Defining_Identifier (Decl), Discr_Map);
7517                Next_Discriminant (Disc);
7518                Next (Decl);
7519             end loop;
7520          end;
7521       end if;
7522
7523       --  Fill in the component declarations
7524
7525       --  Add components for entry families. For each entry family, create an
7526       --  anonymous type declaration with the same size, and analyze the type.
7527
7528       Collect_Entry_Families (Loc, Cdecls, Current_Node, Prot_Typ);
7529
7530       --  Prepend the _Object field with the right type to the component list.
7531       --  We need to compute the number of entries, and in some cases the
7532       --  number of Attach_Handler pragmas.
7533
7534       declare
7535          Ritem              : Node_Id;
7536          Num_Attach_Handler : Int := 0;
7537          Protection_Subtype : Node_Id;
7538          Entry_Count_Expr   : constant Node_Id :=
7539                                 Build_Entry_Count_Expression
7540                                   (Prot_Typ, Cdecls, Loc);
7541
7542       begin
7543          --  Could this be simplified using Corresponding_Runtime_Package???
7544
7545          if Has_Attach_Handler (Prot_Typ) then
7546             Ritem := First_Rep_Item (Prot_Typ);
7547             while Present (Ritem) loop
7548                if Nkind (Ritem) = N_Pragma
7549                  and then Pragma_Name (Ritem) = Name_Attach_Handler
7550                then
7551                   Num_Attach_Handler := Num_Attach_Handler + 1;
7552                end if;
7553
7554                Next_Rep_Item (Ritem);
7555             end loop;
7556
7557             if Restricted_Profile then
7558                if Has_Entries (Prot_Typ) then
7559                   Protection_Subtype :=
7560                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
7561                else
7562                   Protection_Subtype :=
7563                     New_Reference_To (RTE (RE_Protection), Loc);
7564                end if;
7565             else
7566                Protection_Subtype :=
7567                  Make_Subtype_Indication
7568                    (Sloc => Loc,
7569                     Subtype_Mark =>
7570                       New_Reference_To
7571                         (RTE (RE_Static_Interrupt_Protection), Loc),
7572                     Constraint =>
7573                       Make_Index_Or_Discriminant_Constraint (
7574                         Sloc => Loc,
7575                         Constraints => New_List (
7576                           Entry_Count_Expr,
7577                           Make_Integer_Literal (Loc, Num_Attach_Handler))));
7578             end if;
7579
7580          elsif Has_Interrupt_Handler (Prot_Typ) then
7581             Protection_Subtype :=
7582                Make_Subtype_Indication (
7583                  Sloc => Loc,
7584                  Subtype_Mark => New_Reference_To
7585                    (RTE (RE_Dynamic_Interrupt_Protection), Loc),
7586                  Constraint =>
7587                    Make_Index_Or_Discriminant_Constraint (
7588                      Sloc => Loc,
7589                      Constraints => New_List (Entry_Count_Expr)));
7590
7591          --  Type has explicit entries or generated primitive entry wrappers
7592
7593          elsif Has_Entries (Prot_Typ)
7594            or else (Ada_Version >= Ada_05
7595                       and then Present (Interface_List (N)))
7596          then
7597             case Corresponding_Runtime_Package (Prot_Typ) is
7598                when System_Tasking_Protected_Objects_Entries =>
7599                   Protection_Subtype :=
7600                      Make_Subtype_Indication (Loc,
7601                        Subtype_Mark =>
7602                          New_Reference_To (RTE (RE_Protection_Entries), Loc),
7603                        Constraint =>
7604                          Make_Index_Or_Discriminant_Constraint (
7605                            Sloc => Loc,
7606                            Constraints => New_List (Entry_Count_Expr)));
7607
7608                when System_Tasking_Protected_Objects_Single_Entry =>
7609                   Protection_Subtype :=
7610                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
7611
7612                when others =>
7613                   raise Program_Error;
7614             end case;
7615
7616          else
7617             Protection_Subtype := New_Reference_To (RTE (RE_Protection), Loc);
7618          end if;
7619
7620          Object_Comp :=
7621            Make_Component_Declaration (Loc,
7622              Defining_Identifier =>
7623                Make_Defining_Identifier (Loc, Name_uObject),
7624              Component_Definition =>
7625                Make_Component_Definition (Loc,
7626                  Aliased_Present    => True,
7627                  Subtype_Indication => Protection_Subtype));
7628       end;
7629
7630       pragma Assert (Present (Pdef));
7631
7632       --  Add private field components
7633
7634       if Present (Private_Declarations (Pdef)) then
7635          Priv := First (Private_Declarations (Pdef));
7636
7637          while Present (Priv) loop
7638
7639             if Nkind (Priv) = N_Component_Declaration then
7640
7641                --  The component definition consists of a subtype indication,
7642                --  or (in Ada 2005) an access definition. Make a copy of the
7643                --  proper definition.
7644
7645                declare
7646                   Old_Comp : constant Node_Id   := Component_Definition (Priv);
7647                   Pent     : constant Entity_Id := Defining_Identifier (Priv);
7648                   New_Comp : Node_Id;
7649
7650                begin
7651                   if Present (Subtype_Indication (Old_Comp)) then
7652                      New_Comp :=
7653                        Make_Component_Definition (Sloc (Pent),
7654                          Aliased_Present    => False,
7655                          Subtype_Indication =>
7656                            New_Copy_Tree (Subtype_Indication (Old_Comp),
7657                                            Discr_Map));
7658                   else
7659                      New_Comp :=
7660                        Make_Component_Definition (Sloc (Pent),
7661                          Aliased_Present    => False,
7662                          Access_Definition  =>
7663                            New_Copy_Tree (Access_Definition (Old_Comp),
7664                                            Discr_Map));
7665                   end if;
7666
7667                   New_Priv :=
7668                     Make_Component_Declaration (Loc,
7669                       Defining_Identifier =>
7670                         Make_Defining_Identifier (Sloc (Pent), Chars (Pent)),
7671                       Component_Definition => New_Comp,
7672                       Expression => Expression (Priv));
7673
7674                   Append_To (Cdecls, New_Priv);
7675                end;
7676
7677             elsif Nkind (Priv) = N_Subprogram_Declaration then
7678
7679                --  Make the unprotected version of the subprogram available
7680                --  for expansion of intra object calls. There is need for
7681                --  a protected version only if the subprogram is an interrupt
7682                --  handler, otherwise  this operation can only be called from
7683                --  within the body.
7684
7685                Sub :=
7686                  Make_Subprogram_Declaration (Loc,
7687                    Specification =>
7688                      Build_Protected_Sub_Specification
7689                        (Priv, Prot_Typ, Unprotected_Mode));
7690
7691                Insert_After (Current_Node, Sub);
7692                Analyze (Sub);
7693
7694                Set_Protected_Body_Subprogram
7695                  (Defining_Unit_Name (Specification (Priv)),
7696                   Defining_Unit_Name (Specification (Sub)));
7697
7698                Current_Node := Sub;
7699
7700                Sub :=
7701                  Make_Subprogram_Declaration (Loc,
7702                    Specification =>
7703                      Build_Protected_Sub_Specification
7704                        (Priv, Prot_Typ, Protected_Mode));
7705
7706                Insert_After (Current_Node, Sub);
7707                Analyze (Sub);
7708                Current_Node := Sub;
7709
7710                if Is_Interrupt_Handler
7711                  (Defining_Unit_Name (Specification (Priv)))
7712                then
7713                   if not Restricted_Profile then
7714                      Register_Handler;
7715                   end if;
7716                end if;
7717             end if;
7718
7719             Next (Priv);
7720          end loop;
7721       end if;
7722
7723       --  Put the _Object component after the private component so that it
7724       --  be finalized early as required by 9.4 (20)
7725
7726       Append_To (Cdecls, Object_Comp);
7727
7728       Insert_After (Current_Node, Rec_Decl);
7729       Current_Node := Rec_Decl;
7730
7731       --  Analyze the record declaration immediately after construction,
7732       --  because the initialization procedure is needed for single object
7733       --  declarations before the next entity is analyzed (the freeze call
7734       --  that generates this initialization procedure is found below).
7735
7736       Analyze (Rec_Decl, Suppress => All_Checks);
7737
7738       --  Ada 2005 (AI-345): Construct the primitive entry wrappers before
7739       --  the corresponding record is frozen. If any wrappers are generated,
7740       --  Current_Node is updated accordingly.
7741
7742       if Ada_Version >= Ada_05 then
7743          Build_Wrapper_Specs (Loc, Prot_Typ, Current_Node);
7744       end if;
7745
7746       --  Collect pointers to entry bodies and their barriers, to be placed
7747       --  in the Entry_Bodies_Array for the type. For each entry/family we
7748       --  add an expression to the aggregate which is the initial value of
7749       --  this array. The array is declared after all protected subprograms.
7750
7751       if Has_Entries (Prot_Typ) then
7752          Entries_Aggr := Make_Aggregate (Loc, Expressions => New_List);
7753       else
7754          Entries_Aggr := Empty;
7755       end if;
7756
7757       --  Build two new procedure specifications for each protected subprogram;
7758       --  one to call from outside the object and one to call from inside.
7759       --  Build a barrier function and an entry body action procedure
7760       --  specification for each protected entry. Initialize the entry body
7761       --  array. If subprogram is flagged as eliminated, do not generate any
7762       --  internal operations.
7763
7764       E_Count := 0;
7765
7766       Comp := First (Visible_Declarations (Pdef));
7767
7768       while Present (Comp) loop
7769          if Nkind (Comp) = N_Subprogram_Declaration
7770            and then not Is_Eliminated (Defining_Entity (Comp))
7771          then
7772             Sub :=
7773               Make_Subprogram_Declaration (Loc,
7774                 Specification =>
7775                   Build_Protected_Sub_Specification
7776                     (Comp, Prot_Typ, Unprotected_Mode));
7777
7778             Insert_After (Current_Node, Sub);
7779             Analyze (Sub);
7780
7781             Set_Protected_Body_Subprogram
7782               (Defining_Unit_Name (Specification (Comp)),
7783                Defining_Unit_Name (Specification (Sub)));
7784
7785             --  Make the protected version of the subprogram available for
7786             --  expansion of external calls.
7787
7788             Current_Node := Sub;
7789
7790             Sub :=
7791               Make_Subprogram_Declaration (Loc,
7792                 Specification =>
7793                   Build_Protected_Sub_Specification
7794                     (Comp, Prot_Typ, Protected_Mode));
7795
7796             Insert_After (Current_Node, Sub);
7797             Analyze (Sub);
7798
7799             Current_Node := Sub;
7800
7801             --  Generate an overriding primitive operation specification for
7802             --  this subprogram if the protected type implements an interface.
7803
7804             if Ada_Version >= Ada_05
7805               and then
7806                 Present (Interfaces (Corresponding_Record_Type (Prot_Typ)))
7807             then
7808                Sub :=
7809                  Make_Subprogram_Declaration (Loc,
7810                    Specification =>
7811                      Build_Protected_Sub_Specification
7812                        (Comp, Prot_Typ, Dispatching_Mode));
7813
7814                Insert_After (Current_Node, Sub);
7815                Analyze (Sub);
7816
7817                Current_Node := Sub;
7818             end if;
7819
7820             --  If a pragma Interrupt_Handler applies, build and add a call to
7821             --  Register_Interrupt_Handler to the freezing actions of the
7822             --  protected version (Current_Node) of the subprogram:
7823
7824             --    system.interrupts.register_interrupt_handler
7825             --       (prot_procP'address);
7826
7827             if not Restricted_Profile
7828               and then Is_Interrupt_Handler
7829                          (Defining_Unit_Name (Specification (Comp)))
7830             then
7831                Register_Handler;
7832             end if;
7833
7834          elsif Nkind (Comp) = N_Entry_Declaration then
7835             E_Count := E_Count + 1;
7836             Comp_Id := Defining_Identifier (Comp);
7837
7838             Edef :=
7839               Make_Defining_Identifier (Loc,
7840                 Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
7841             Sub :=
7842               Make_Subprogram_Declaration (Loc,
7843                 Specification =>
7844                   Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
7845
7846             Insert_After (Current_Node, Sub);
7847             Analyze (Sub);
7848
7849             Set_Protected_Body_Subprogram
7850               (Defining_Identifier (Comp),
7851                Defining_Unit_Name (Specification (Sub)));
7852
7853             Current_Node := Sub;
7854
7855             Bdef :=
7856               Make_Defining_Identifier (Loc,
7857                 Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'B'));
7858             Sub :=
7859               Make_Subprogram_Declaration (Loc,
7860                 Specification =>
7861                   Build_Barrier_Function_Specification (Loc, Bdef));
7862
7863             Insert_After (Current_Node, Sub);
7864             Analyze (Sub);
7865             Set_Protected_Body_Subprogram (Bdef, Bdef);
7866             Set_Barrier_Function (Comp_Id, Bdef);
7867             Set_Scope (Bdef, Scope (Comp_Id));
7868             Current_Node := Sub;
7869
7870             --  Collect pointers to the protected subprogram and the barrier
7871             --  of the current entry, for insertion into Entry_Bodies_Array.
7872
7873             Append (
7874               Make_Aggregate (Loc,
7875                 Expressions => New_List (
7876                   Make_Attribute_Reference (Loc,
7877                     Prefix => New_Reference_To (Bdef, Loc),
7878                     Attribute_Name => Name_Unrestricted_Access),
7879                   Make_Attribute_Reference (Loc,
7880                     Prefix => New_Reference_To (Edef, Loc),
7881                     Attribute_Name => Name_Unrestricted_Access))),
7882               Expressions (Entries_Aggr));
7883
7884          end if;
7885
7886          Next (Comp);
7887       end loop;
7888
7889       --  If there are some private entry declarations, expand it as if they
7890       --  were visible entries.
7891
7892       if Present (Private_Declarations (Pdef)) then
7893          Comp := First (Private_Declarations (Pdef));
7894          while Present (Comp) loop
7895             if Nkind (Comp) = N_Entry_Declaration then
7896                E_Count := E_Count + 1;
7897                Comp_Id := Defining_Identifier (Comp);
7898
7899                Edef :=
7900                  Make_Defining_Identifier (Loc,
7901                   Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
7902                Sub :=
7903                  Make_Subprogram_Declaration (Loc,
7904                    Specification =>
7905                      Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
7906
7907                Insert_After (Current_Node, Sub);
7908                Analyze (Sub);
7909
7910                Set_Protected_Body_Subprogram
7911                  (Defining_Identifier (Comp),
7912                   Defining_Unit_Name (Specification (Sub)));
7913
7914                Current_Node := Sub;
7915
7916                Bdef :=
7917                  Make_Defining_Identifier (Loc,
7918                    Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
7919
7920                Sub :=
7921                  Make_Subprogram_Declaration (Loc,
7922                    Specification =>
7923                      Build_Barrier_Function_Specification (Loc, Bdef));
7924
7925                Insert_After (Current_Node, Sub);
7926                Analyze (Sub);
7927                Set_Protected_Body_Subprogram (Bdef, Bdef);
7928                Set_Barrier_Function (Comp_Id, Bdef);
7929                Set_Scope (Bdef, Scope (Comp_Id));
7930                Current_Node := Sub;
7931
7932                --  Collect pointers to the protected subprogram and the barrier
7933                --  of the current entry, for insertion into Entry_Bodies_Array.
7934
7935                Append_To (Expressions (Entries_Aggr),
7936                  Make_Aggregate (Loc,
7937                    Expressions => New_List (
7938                      Make_Attribute_Reference (Loc,
7939                        Prefix => New_Reference_To (Bdef, Loc),
7940                        Attribute_Name => Name_Unrestricted_Access),
7941                      Make_Attribute_Reference (Loc,
7942                        Prefix => New_Reference_To (Edef, Loc),
7943                        Attribute_Name => Name_Unrestricted_Access))));
7944             end if;
7945
7946             Next (Comp);
7947          end loop;
7948       end if;
7949
7950       --  Emit declaration for Entry_Bodies_Array, now that the addresses of
7951       --  all protected subprograms have been collected.
7952
7953       if Has_Entries (Prot_Typ) then
7954          Body_Id :=
7955            Make_Defining_Identifier (Sloc (Prot_Typ),
7956              Chars => New_External_Name (Chars (Prot_Typ), 'A'));
7957
7958          case Corresponding_Runtime_Package (Prot_Typ) is
7959             when System_Tasking_Protected_Objects_Entries =>
7960                Body_Arr := Make_Object_Declaration (Loc,
7961                  Defining_Identifier => Body_Id,
7962                  Aliased_Present => True,
7963                  Object_Definition =>
7964                    Make_Subtype_Indication (Loc,
7965                      Subtype_Mark => New_Reference_To (
7966                        RTE (RE_Protected_Entry_Body_Array), Loc),
7967                      Constraint =>
7968                        Make_Index_Or_Discriminant_Constraint (Loc,
7969                          Constraints => New_List (
7970                             Make_Range (Loc,
7971                               Make_Integer_Literal (Loc, 1),
7972                               Make_Integer_Literal (Loc, E_Count))))),
7973                  Expression => Entries_Aggr);
7974
7975             when System_Tasking_Protected_Objects_Single_Entry =>
7976                Body_Arr := Make_Object_Declaration (Loc,
7977                  Defining_Identifier => Body_Id,
7978                  Aliased_Present => True,
7979                  Object_Definition => New_Reference_To
7980                                         (RTE (RE_Entry_Body), Loc),
7981                  Expression =>
7982                    Make_Aggregate (Loc,
7983                      Expressions => New_List (
7984                        Make_Attribute_Reference (Loc,
7985                          Prefix => New_Reference_To (Bdef, Loc),
7986                          Attribute_Name => Name_Unrestricted_Access),
7987                        Make_Attribute_Reference (Loc,
7988                          Prefix => New_Reference_To (Edef, Loc),
7989                          Attribute_Name => Name_Unrestricted_Access))));
7990
7991             when others =>
7992                raise Program_Error;
7993          end case;
7994
7995          --  A pointer to this array will be placed in the corresponding record
7996          --  by its initialization procedure so this needs to be analyzed here.
7997
7998          Insert_After (Current_Node, Body_Arr);
7999          Current_Node := Body_Arr;
8000          Analyze (Body_Arr);
8001
8002          Set_Entry_Bodies_Array (Prot_Typ, Body_Id);
8003
8004          --  Finally, build the function that maps an entry index into the
8005          --  corresponding body. A pointer to this function is placed in each
8006          --  object of the type. Except for a ravenscar-like profile (no abort,
8007          --  no entry queue, 1 entry)
8008
8009          if Corresponding_Runtime_Package (Prot_Typ) =
8010               System_Tasking_Protected_Objects_Entries
8011          then
8012             Sub :=
8013               Make_Subprogram_Declaration (Loc,
8014                 Specification => Build_Find_Body_Index_Spec (Prot_Typ));
8015             Insert_After (Current_Node, Sub);
8016             Analyze (Sub);
8017          end if;
8018       end if;
8019    end Expand_N_Protected_Type_Declaration;
8020
8021    --------------------------------
8022    -- Expand_N_Requeue_Statement --
8023    --------------------------------
8024
8025    --  A non-dispatching requeue statement is expanded into one of four GNARLI
8026    --  operations, depending on the source and destination (task or protected
8027    --  object). A dispatching requeue statement is expanded into a call to the
8028    --  predefined primitive _Disp_Requeue. In addition, code is generated to
8029    --  jump around the remainder of processing for the original entry and, if
8030    --  the destination is (different) protected object, to attempt to service
8031    --  it. The following illustrates the various cases:
8032
8033    --  procedure entE
8034    --    (O : System.Address;
8035    --     P : System.Address;
8036    --     E : Protected_Entry_Index)
8037    --  is
8038    --     <discriminant renamings>
8039    --     <private object renamings>
8040    --     type poVP is access poV;
8041    --     _object : ptVP := ptVP!(O);
8042
8043    --  begin
8044    --     begin
8045    --        <start of statement sequence for entry>
8046
8047    --        -- Requeue from one protected entry body to another protected
8048    --        -- entry.
8049
8050    --        Requeue_Protected_Entry (
8051    --          _object._object'Access,
8052    --          new._object'Access,
8053    --          E,
8054    --          Abort_Present);
8055    --        return;
8056
8057    --        <some more of the statement sequence for entry>
8058
8059    --        --  Requeue from an entry body to a task entry
8060
8061    --        Requeue_Protected_To_Task_Entry (
8062    --          New._task_id,
8063    --          E,
8064    --          Abort_Present);
8065    --        return;
8066
8067    --        <rest of statement sequence for entry>
8068    --        Complete_Entry_Body (_object._object);
8069
8070    --     exception
8071    --        when all others =>
8072    --           Exceptional_Complete_Entry_Body (
8073    --             _object._object, Get_GNAT_Exception);
8074    --     end;
8075    --  end entE;
8076
8077    --  Requeue of a task entry call to a task entry
8078
8079    --  Accept_Call (E, Ann);
8080    --     <start of statement sequence for accept statement>
8081    --     Requeue_Task_Entry (New._task_id, E, Abort_Present);
8082    --     goto Lnn;
8083    --     <rest of statement sequence for accept statement>
8084    --     <<Lnn>>
8085    --     Complete_Rendezvous;
8086
8087    --  exception
8088    --     when all others =>
8089    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8090
8091    --  Requeue of a task entry call to a protected entry
8092
8093    --  Accept_Call (E, Ann);
8094    --     <start of statement sequence for accept statement>
8095    --     Requeue_Task_To_Protected_Entry (
8096    --       new._object'Access,
8097    --       E,
8098    --       Abort_Present);
8099    --     newS (new, Pnn);
8100    --     goto Lnn;
8101    --     <rest of statement sequence for accept statement>
8102    --     <<Lnn>>
8103    --     Complete_Rendezvous;
8104
8105    --  exception
8106    --     when all others =>
8107    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8108
8109    --  Ada 2005 (AI05-0030): Dispatching requeue from protected to interface
8110    --  class-wide type:
8111
8112    --  procedure entE
8113    --    (O : System.Address;
8114    --     P : System.Address;
8115    --     E : Protected_Entry_Index)
8116    --  is
8117    --     <discriminant renamings>
8118    --     <private object renamings>
8119    --     type poVP is access poV;
8120    --     _object : ptVP := ptVP!(O);
8121
8122    --  begin
8123    --     begin
8124    --        <start of statement sequence for entry>
8125
8126    --        _Disp_Requeue
8127    --          (<interface class-wide object>,
8128    --           True,
8129    --           _object'Address,
8130    --           Ada.Tags.Get_Offset_Index
8131    --             (Tag (_object),
8132    --              <interface dispatch table index of target entry>),
8133    --           Abort_Present);
8134    --        return;
8135
8136    --        <rest of statement sequence for entry>
8137    --        Complete_Entry_Body (_object._object);
8138
8139    --     exception
8140    --        when all others =>
8141    --           Exceptional_Complete_Entry_Body (
8142    --             _object._object, Get_GNAT_Exception);
8143    --     end;
8144    --  end entE;
8145
8146    --  Ada 2005 (AI05-0030): Dispatching requeue from task to interface
8147    --  class-wide type:
8148
8149    --  Accept_Call (E, Ann);
8150    --     <start of statement sequence for accept statement>
8151    --     _Disp_Requeue
8152    --       (<interface class-wide object>,
8153    --        False,
8154    --        null,
8155    --        Ada.Tags.Get_Offset_Index
8156    --          (Tag (_object),
8157    --           <interface dispatch table index of target entrt>),
8158    --        Abort_Present);
8159    --     newS (new, Pnn);
8160    --     goto Lnn;
8161    --     <rest of statement sequence for accept statement>
8162    --     <<Lnn>>
8163    --     Complete_Rendezvous;
8164
8165    --  exception
8166    --     when all others =>
8167    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8168
8169    --  Further details on these expansions can be found in Expand_N_Protected_
8170    --  Body and Expand_N_Accept_Statement.
8171
8172    procedure Expand_N_Requeue_Statement (N : Node_Id) is
8173       Loc        : constant Source_Ptr := Sloc (N);
8174       Abortable  : Node_Id;
8175       Acc_Stat   : Node_Id;
8176       Conc_Typ   : Entity_Id;
8177       Concval    : Node_Id;
8178       Ename      : Node_Id;
8179       Index      : Node_Id;
8180       Lab_Node   : Node_Id;
8181       New_Param  : Node_Id;
8182       Old_Typ    : Entity_Id;
8183       Params     : List_Id;
8184       Rcall      : Node_Id;
8185       RTS_Call   : Entity_Id;
8186       Self_Param : Node_Id;
8187       Skip_Stat  : Node_Id;
8188
8189    begin
8190       Abortable :=
8191         New_Occurrence_Of (Boolean_Literals (Abort_Present (N)), Loc);
8192
8193       --  Extract the components of the entry call
8194
8195       Extract_Entry (N, Concval, Ename, Index);
8196       Conc_Typ := Etype (Concval);
8197
8198       --  Examine the scope stack in order to find nearest enclosing protected
8199       --  or task type. This will constitute our invocation source.
8200
8201       Old_Typ := Current_Scope;
8202       while Present (Old_Typ)
8203         and then not Is_Protected_Type (Old_Typ)
8204         and then not Is_Task_Type (Old_Typ)
8205       loop
8206          Old_Typ := Scope (Old_Typ);
8207       end loop;
8208
8209       --  Generate the parameter list for all cases. The abortable flag is
8210       --  common among dispatching and regular requeue.
8211
8212       Params := New_List (Abortable);
8213
8214       --  Ada 2005 (AI05-0030): We have a dispatching requeue of the form
8215       --  Concval.Ename where the type of Concval is class-wide concurrent
8216       --  interface.
8217
8218       if Ada_Version >= Ada_05
8219         and then Present (Concval)
8220         and then Is_Class_Wide_Type (Conc_Typ)
8221         and then Is_Concurrent_Interface (Conc_Typ)
8222       then
8223          RTS_Call := Make_Identifier (Loc, Name_uDisp_Requeue);
8224
8225          --  Generate:
8226          --    Ada.Tags.Get_Offset_Index
8227          --      (Ada.Tags.Tag (Concval),
8228          --       <interface dispatch table position of Ename>)
8229
8230          Prepend_To (Params,
8231            Make_Function_Call (Loc,
8232              Name =>
8233                New_Reference_To (RTE (RE_Get_Offset_Index), Loc),
8234              Parameter_Associations =>
8235                New_List (
8236                  Unchecked_Convert_To (RTE (RE_Tag), Concval),
8237                  Make_Integer_Literal (Loc, DT_Position (Entity (Ename))))));
8238
8239          --  Specific actuals for protected to interface class-wide type
8240          --  requeue.
8241
8242          if Is_Protected_Type (Old_Typ) then
8243             Prepend_To (Params,
8244               Make_Attribute_Reference (Loc,        --  _object'Address
8245                 Prefix =>
8246                   Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
8247                 Attribute_Name =>
8248                   Name_Address));
8249             Prepend_To (Params,                     --  True
8250               New_Reference_To (Standard_True, Loc));
8251
8252          --  Specific actuals for task to interface class-wide type requeue
8253
8254          else
8255             pragma Assert (Is_Task_Type (Old_Typ));
8256
8257             Prepend_To (Params,                     --  null
8258               New_Reference_To (RTE (RE_Null_Address), Loc));
8259             Prepend_To (Params,                     --  False
8260               New_Reference_To (Standard_False, Loc));
8261          end if;
8262
8263          --  Finally, add the common object parameter
8264
8265          Prepend_To (Params, New_Copy_Tree (Concval));
8266
8267       --  Regular requeue processing
8268
8269       else
8270          New_Param := Concurrent_Ref (Concval);
8271
8272          --  The index expression is common among all four cases
8273
8274          Prepend_To (Params,
8275            Entry_Index_Expression (Loc, Entity (Ename), Index, Conc_Typ));
8276
8277          if Is_Protected_Type (Old_Typ) then
8278             Self_Param :=
8279               Make_Attribute_Reference (Loc,
8280                 Prefix =>
8281                   Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
8282                 Attribute_Name =>
8283                   Name_Unchecked_Access);
8284
8285             --  Protected to protected requeue
8286
8287             if Is_Protected_Type (Conc_Typ) then
8288                RTS_Call :=
8289                  New_Reference_To (RTE (RE_Requeue_Protected_Entry), Loc);
8290
8291                New_Param :=
8292                  Make_Attribute_Reference (Loc,
8293                    Prefix =>
8294                      New_Param,
8295                    Attribute_Name =>
8296                      Name_Unchecked_Access);
8297
8298             --  Protected to task requeue
8299
8300             else
8301                pragma Assert (Is_Task_Type (Conc_Typ));
8302                RTS_Call :=
8303                  New_Reference_To (
8304                    RTE (RE_Requeue_Protected_To_Task_Entry), Loc);
8305             end if;
8306
8307             Prepend (New_Param, Params);
8308             Prepend (Self_Param, Params);
8309
8310          else
8311             pragma Assert (Is_Task_Type (Old_Typ));
8312
8313             --  Task to protected requeue
8314
8315             if Is_Protected_Type (Conc_Typ) then
8316                RTS_Call :=
8317                  New_Reference_To (
8318                    RTE (RE_Requeue_Task_To_Protected_Entry), Loc);
8319
8320                New_Param :=
8321                  Make_Attribute_Reference (Loc,
8322                    Prefix =>
8323                      New_Param,
8324                    Attribute_Name =>
8325                      Name_Unchecked_Access);
8326
8327             --  Task to task requeue
8328
8329             else
8330                pragma Assert (Is_Task_Type (Conc_Typ));
8331                RTS_Call :=
8332                  New_Reference_To (RTE (RE_Requeue_Task_Entry), Loc);
8333             end if;
8334
8335             Prepend (New_Param, Params);
8336          end if;
8337       end if;
8338
8339       --  Create the GNARLI or predefined primitive call
8340
8341       Rcall :=
8342         Make_Procedure_Call_Statement (Loc,
8343           Name => RTS_Call,
8344           Parameter_Associations => Params);
8345
8346       Rewrite (N, Rcall);
8347       Analyze (N);
8348
8349       if Is_Protected_Type (Old_Typ) then
8350
8351          --  Build the return statement to skip the rest of the entry body
8352
8353          Skip_Stat := Make_Simple_Return_Statement (Loc);
8354
8355       else
8356          --  If the requeue is within a task, find the end label of the
8357          --  enclosing accept statement.
8358
8359          Acc_Stat := Parent (N);
8360          while Nkind (Acc_Stat) /= N_Accept_Statement loop
8361             Acc_Stat := Parent (Acc_Stat);
8362          end loop;
8363
8364          --  The last statement is the second label, used for completing the
8365          --  rendezvous the usual way. The label we are looking for is right
8366          --  before it.
8367
8368          Lab_Node :=
8369            Prev (Last (Statements (Handled_Statement_Sequence (Acc_Stat))));
8370
8371          pragma Assert (Nkind (Lab_Node) = N_Label);
8372
8373          --  Build the goto statement to skip the rest of the accept
8374          --  statement.
8375
8376          Skip_Stat :=
8377            Make_Goto_Statement (Loc,
8378              Name => New_Occurrence_Of (Entity (Identifier (Lab_Node)), Loc));
8379       end if;
8380
8381       Set_Analyzed (Skip_Stat);
8382
8383       Insert_After (N, Skip_Stat);
8384    end Expand_N_Requeue_Statement;
8385
8386    -------------------------------
8387    -- Expand_N_Selective_Accept --
8388    -------------------------------
8389
8390    procedure Expand_N_Selective_Accept (N : Node_Id) is
8391       Loc            : constant Source_Ptr := Sloc (N);
8392       Alts           : constant List_Id    := Select_Alternatives (N);
8393
8394       --  Note: in the below declarations a lot of new lists are allocated
8395       --  unconditionally which may well not end up being used. That's
8396       --  not a good idea since it wastes space gratuitously ???
8397
8398       Accept_Case    : List_Id;
8399       Accept_List    : constant List_Id := New_List;
8400
8401       Alt            : Node_Id;
8402       Alt_List       : constant List_Id := New_List;
8403       Alt_Stats      : List_Id;
8404       Ann            : Entity_Id := Empty;
8405
8406       Block          : Node_Id;
8407       Check_Guard    : Boolean := True;
8408
8409       Decls          : constant List_Id := New_List;
8410       Stats          : constant List_Id := New_List;
8411       Body_List      : constant List_Id := New_List;
8412       Trailing_List  : constant List_Id := New_List;
8413
8414       Choices        : List_Id;
8415       Else_Present   : Boolean := False;
8416       Terminate_Alt  : Node_Id := Empty;
8417       Select_Mode    : Node_Id;
8418
8419       Delay_Case     : List_Id;
8420       Delay_Count    : Integer := 0;
8421       Delay_Val      : Entity_Id;
8422       Delay_Index    : Entity_Id;
8423       Delay_Min      : Entity_Id;
8424       Delay_Num      : Int := 1;
8425       Delay_Alt_List : List_Id := New_List;
8426       Delay_List     : constant List_Id := New_List;
8427       D              : Entity_Id;
8428       M              : Entity_Id;
8429
8430       First_Delay    : Boolean := True;
8431       Guard_Open     : Entity_Id;
8432
8433       End_Lab        : Node_Id;
8434       Index          : Int := 1;
8435       Lab            : Node_Id;
8436       Num_Alts       : Int;
8437       Num_Accept     : Nat := 0;
8438       Proc           : Node_Id;
8439       Q              : Node_Id;
8440       Time_Type      : Entity_Id;
8441       X              : Node_Id;
8442       Select_Call    : Node_Id;
8443
8444       Qnam : constant Entity_Id :=
8445                Make_Defining_Identifier (Loc, New_External_Name ('S', 0));
8446
8447       Xnam : constant Entity_Id :=
8448                Make_Defining_Identifier (Loc, New_External_Name ('J', 1));
8449
8450       -----------------------
8451       -- Local subprograms --
8452       -----------------------
8453
8454       function Accept_Or_Raise return List_Id;
8455       --  For the rare case where delay alternatives all have guards, and
8456       --  all of them are closed, it is still possible that there were open
8457       --  accept alternatives with no callers. We must reexamine the
8458       --  Accept_List, and execute a selective wait with no else if some
8459       --  accept is open. If none, we raise program_error.
8460
8461       procedure Add_Accept (Alt : Node_Id);
8462       --  Process a single accept statement in a select alternative. Build
8463       --  procedure for body of accept, and add entry to dispatch table with
8464       --  expression for guard, in preparation for call to run time select.
8465
8466       function Make_And_Declare_Label (Num : Int) return Node_Id;
8467       --  Manufacture a label using Num as a serial number and declare it.
8468       --  The declaration is appended to Decls. The label marks the trailing
8469       --  statements of an accept or delay alternative.
8470
8471       function Make_Select_Call (Select_Mode : Entity_Id) return Node_Id;
8472       --  Build call to Selective_Wait runtime routine
8473
8474       procedure Process_Delay_Alternative (Alt : Node_Id; Index : Int);
8475       --  Add code to compare value of delay with previous values, and
8476       --  generate case entry for trailing statements.
8477
8478       procedure Process_Accept_Alternative
8479         (Alt   : Node_Id;
8480          Index : Int;
8481          Proc  : Node_Id);
8482       --  Add code to call corresponding procedure, and branch to
8483       --  trailing statements, if any.
8484
8485       ---------------------
8486       -- Accept_Or_Raise --
8487       ---------------------
8488
8489       function Accept_Or_Raise return List_Id is
8490          Cond  : Node_Id;
8491          Stats : List_Id;
8492          J     : constant Entity_Id := Make_Defining_Identifier (Loc,
8493                                                   New_Internal_Name ('J'));
8494
8495       begin
8496          --  We generate the following:
8497
8498          --    for J in q'range loop
8499          --       if q(J).S /=null_task_entry then
8500          --          selective_wait (simple_mode,...);
8501          --          done := True;
8502          --          exit;
8503          --       end if;
8504          --    end loop;
8505          --
8506          --    if no rendez_vous then
8507          --       raise program_error;
8508          --    end if;
8509
8510          --    Note that the code needs to know that the selector name
8511          --    in an Accept_Alternative is named S.
8512
8513          Cond := Make_Op_Ne (Loc,
8514            Left_Opnd =>
8515              Make_Selected_Component (Loc,
8516                Prefix => Make_Indexed_Component (Loc,
8517                  Prefix => New_Reference_To (Qnam, Loc),
8518                    Expressions => New_List (New_Reference_To (J, Loc))),
8519              Selector_Name => Make_Identifier (Loc, Name_S)),
8520            Right_Opnd =>
8521              New_Reference_To (RTE (RE_Null_Task_Entry), Loc));
8522
8523          Stats := New_List (
8524            Make_Implicit_Loop_Statement (N,
8525              Identifier => Empty,
8526              Iteration_Scheme =>
8527                Make_Iteration_Scheme (Loc,
8528                  Loop_Parameter_Specification =>
8529                    Make_Loop_Parameter_Specification (Loc,
8530                      Defining_Identifier => J,
8531                      Discrete_Subtype_Definition =>
8532                        Make_Attribute_Reference (Loc,
8533                          Prefix => New_Reference_To (Qnam, Loc),
8534                          Attribute_Name => Name_Range,
8535                          Expressions => New_List (
8536                            Make_Integer_Literal (Loc, 1))))),
8537
8538              Statements => New_List (
8539                Make_Implicit_If_Statement (N,
8540                  Condition =>  Cond,
8541                  Then_Statements => New_List (
8542                    Make_Select_Call (
8543                     New_Reference_To (RTE (RE_Simple_Mode), Loc)),
8544                    Make_Exit_Statement (Loc))))));
8545
8546          Append_To (Stats,
8547            Make_Raise_Program_Error (Loc,
8548              Condition => Make_Op_Eq (Loc,
8549                Left_Opnd  => New_Reference_To (Xnam, Loc),
8550                Right_Opnd =>
8551                  New_Reference_To (RTE (RE_No_Rendezvous), Loc)),
8552              Reason => PE_All_Guards_Closed));
8553
8554          return Stats;
8555       end Accept_Or_Raise;
8556
8557       ----------------
8558       -- Add_Accept --
8559       ----------------
8560
8561       procedure Add_Accept (Alt : Node_Id) is
8562          Acc_Stm   : constant Node_Id    := Accept_Statement (Alt);
8563          Ename     : constant Node_Id    := Entry_Direct_Name (Acc_Stm);
8564          Eloc      : constant Source_Ptr := Sloc (Ename);
8565          Eent      : constant Entity_Id  := Entity (Ename);
8566          Index     : constant Node_Id    := Entry_Index (Acc_Stm);
8567          Null_Body : Node_Id;
8568          Proc_Body : Node_Id;
8569          PB_Ent    : Entity_Id;
8570          Expr      : Node_Id;
8571          Call      : Node_Id;
8572
8573       begin
8574          if No (Ann) then
8575             Ann := Node (Last_Elmt (Accept_Address (Eent)));
8576          end if;
8577
8578          if Present (Condition (Alt)) then
8579             Expr :=
8580               Make_Conditional_Expression (Eloc, New_List (
8581                 Condition (Alt),
8582                 Entry_Index_Expression (Eloc, Eent, Index, Scope (Eent)),
8583                 New_Reference_To (RTE (RE_Null_Task_Entry), Eloc)));
8584          else
8585             Expr :=
8586               Entry_Index_Expression
8587                 (Eloc, Eent, Index, Scope (Eent));
8588          end if;
8589
8590          if Present (Handled_Statement_Sequence (Accept_Statement (Alt))) then
8591             Null_Body := New_Reference_To (Standard_False, Eloc);
8592
8593             if Abort_Allowed then
8594                Call := Make_Procedure_Call_Statement (Eloc,
8595                  Name => New_Reference_To (RTE (RE_Abort_Undefer), Eloc));
8596                Insert_Before (First (Statements (Handled_Statement_Sequence (
8597                  Accept_Statement (Alt)))), Call);
8598                Analyze (Call);
8599             end if;
8600
8601             PB_Ent :=
8602               Make_Defining_Identifier (Eloc,
8603                 New_External_Name (Chars (Ename), 'A', Num_Accept));
8604
8605             if Comes_From_Source (Alt) then
8606                Set_Debug_Info_Needed (PB_Ent);
8607             end if;
8608
8609             Proc_Body :=
8610               Make_Subprogram_Body (Eloc,
8611                 Specification =>
8612                   Make_Procedure_Specification (Eloc,
8613                     Defining_Unit_Name => PB_Ent),
8614                Declarations => Declarations (Acc_Stm),
8615                Handled_Statement_Sequence =>
8616                  Build_Accept_Body (Accept_Statement (Alt)));
8617
8618             --  During the analysis of the body of the accept statement, any
8619             --  zero cost exception handler records were collected in the
8620             --  Accept_Handler_Records field of the N_Accept_Alternative node.
8621             --  This is where we move them to where they belong, namely the
8622             --  newly created procedure.
8623
8624             Set_Handler_Records (PB_Ent, Accept_Handler_Records (Alt));
8625             Append (Proc_Body, Body_List);
8626
8627          else
8628             Null_Body := New_Reference_To (Standard_True,  Eloc);
8629
8630             --  if accept statement has declarations, insert above, given that
8631             --  we are not creating a body for the accept.
8632
8633             if Present (Declarations (Acc_Stm)) then
8634                Insert_Actions (N, Declarations (Acc_Stm));
8635             end if;
8636          end if;
8637
8638          Append_To (Accept_List,
8639            Make_Aggregate (Eloc, Expressions => New_List (Null_Body, Expr)));
8640
8641          Num_Accept := Num_Accept + 1;
8642       end Add_Accept;
8643
8644       ----------------------------
8645       -- Make_And_Declare_Label --
8646       ----------------------------
8647
8648       function Make_And_Declare_Label (Num : Int) return Node_Id is
8649          Lab_Id : Node_Id;
8650
8651       begin
8652          Lab_Id := Make_Identifier (Loc, New_External_Name ('L', Num));
8653          Lab :=
8654            Make_Label (Loc, Lab_Id);
8655
8656          Append_To (Decls,
8657            Make_Implicit_Label_Declaration (Loc,
8658              Defining_Identifier  =>
8659                Make_Defining_Identifier (Loc, Chars (Lab_Id)),
8660              Label_Construct => Lab));
8661
8662          return Lab;
8663       end Make_And_Declare_Label;
8664
8665       ----------------------
8666       -- Make_Select_Call --
8667       ----------------------
8668
8669       function Make_Select_Call (Select_Mode : Entity_Id) return Node_Id is
8670          Params : constant List_Id := New_List;
8671
8672       begin
8673          Append (
8674            Make_Attribute_Reference (Loc,
8675              Prefix => New_Reference_To (Qnam, Loc),
8676              Attribute_Name => Name_Unchecked_Access),
8677            Params);
8678          Append (Select_Mode, Params);
8679          Append (New_Reference_To (Ann, Loc), Params);
8680          Append (New_Reference_To (Xnam, Loc), Params);
8681
8682          return
8683            Make_Procedure_Call_Statement (Loc,
8684              Name => New_Reference_To (RTE (RE_Selective_Wait), Loc),
8685              Parameter_Associations => Params);
8686       end Make_Select_Call;
8687
8688       --------------------------------
8689       -- Process_Accept_Alternative --
8690       --------------------------------
8691
8692       procedure Process_Accept_Alternative
8693         (Alt   : Node_Id;
8694          Index : Int;
8695          Proc  : Node_Id)
8696       is
8697          Choices   : List_Id := No_List;
8698          Alt_Stats : List_Id;
8699
8700       begin
8701          Adjust_Condition (Condition (Alt));
8702          Alt_Stats := No_List;
8703
8704          if Present (Handled_Statement_Sequence (Accept_Statement (Alt))) then
8705             Choices := New_List (
8706               Make_Integer_Literal (Loc, Index));
8707
8708             Alt_Stats := New_List (
8709               Make_Procedure_Call_Statement (Sloc (Proc),
8710                 Name => New_Reference_To (
8711                   Defining_Unit_Name (Specification (Proc)), Sloc (Proc))));
8712          end if;
8713
8714          if Statements (Alt) /= Empty_List then
8715
8716             if No (Alt_Stats) then
8717
8718                --  Accept with no body, followed by trailing statements
8719
8720                Choices := New_List (
8721                  Make_Integer_Literal (Loc, Index));
8722
8723                Alt_Stats := New_List;
8724             end if;
8725
8726             --  After the call, if any, branch to trailing statements. We
8727             --  create a label for each, as well as the corresponding label
8728             --  declaration.
8729
8730             Lab := Make_And_Declare_Label (Index);
8731             Append_To (Alt_Stats,
8732               Make_Goto_Statement (Loc,
8733                 Name => New_Copy (Identifier (Lab))));
8734
8735             Append (Lab, Trailing_List);
8736             Append_List (Statements (Alt), Trailing_List);
8737             Append_To (Trailing_List,
8738               Make_Goto_Statement (Loc,
8739                 Name => New_Copy (Identifier (End_Lab))));
8740          end if;
8741
8742          if Present (Alt_Stats) then
8743
8744             --  Procedure call. and/or trailing statements
8745
8746             Append_To (Alt_List,
8747               Make_Case_Statement_Alternative (Loc,
8748                 Discrete_Choices => Choices,
8749                 Statements => Alt_Stats));
8750          end if;
8751       end Process_Accept_Alternative;
8752
8753       -------------------------------
8754       -- Process_Delay_Alternative --
8755       -------------------------------
8756
8757       procedure Process_Delay_Alternative (Alt : Node_Id; Index : Int) is
8758          Choices   : List_Id;
8759          Cond      : Node_Id;
8760          Delay_Alt : List_Id;
8761
8762       begin
8763          --  Deal with C/Fortran boolean as delay condition
8764
8765          Adjust_Condition (Condition (Alt));
8766
8767          --  Determine the smallest specified delay
8768
8769          --  for each delay alternative generate:
8770
8771          --    if guard-expression then
8772          --       Delay_Val  := delay-expression;
8773          --       Guard_Open := True;
8774          --       if Delay_Val < Delay_Min then
8775          --          Delay_Min   := Delay_Val;
8776          --          Delay_Index := Index;
8777          --       end if;
8778          --    end if;
8779
8780          --  The enclosing if-statement is omitted if there is no guard
8781
8782          if Delay_Count = 1
8783            or else First_Delay
8784          then
8785             First_Delay := False;
8786
8787             Delay_Alt := New_List (
8788               Make_Assignment_Statement (Loc,
8789                 Name => New_Reference_To (Delay_Min, Loc),
8790                 Expression => Expression (Delay_Statement (Alt))));
8791
8792             if Delay_Count > 1 then
8793                Append_To (Delay_Alt,
8794                  Make_Assignment_Statement (Loc,
8795                    Name       => New_Reference_To (Delay_Index, Loc),
8796                    Expression => Make_Integer_Literal (Loc, Index)));
8797             end if;
8798
8799          else
8800             Delay_Alt := New_List (
8801               Make_Assignment_Statement (Loc,
8802                 Name => New_Reference_To (Delay_Val, Loc),
8803                 Expression => Expression (Delay_Statement (Alt))));
8804
8805             if Time_Type = Standard_Duration then
8806                Cond :=
8807                   Make_Op_Lt (Loc,
8808                     Left_Opnd  => New_Reference_To (Delay_Val, Loc),
8809                     Right_Opnd => New_Reference_To (Delay_Min, Loc));
8810
8811             else
8812                --  The scope of the time type must define a comparison
8813                --  operator. The scope itself may not be visible, so we
8814                --  construct a node with entity information to insure that
8815                --  semantic analysis can find the proper operator.
8816
8817                Cond :=
8818                  Make_Function_Call (Loc,
8819                    Name => Make_Selected_Component (Loc,
8820                      Prefix => New_Reference_To (Scope (Time_Type), Loc),
8821                      Selector_Name =>
8822                        Make_Operator_Symbol (Loc,
8823                          Chars => Name_Op_Lt,
8824                          Strval => No_String)),
8825                     Parameter_Associations =>
8826                       New_List (
8827                         New_Reference_To (Delay_Val, Loc),
8828                         New_Reference_To (Delay_Min, Loc)));
8829
8830                Set_Entity (Prefix (Name (Cond)), Scope (Time_Type));
8831             end if;
8832
8833             Append_To (Delay_Alt,
8834               Make_Implicit_If_Statement (N,
8835                 Condition => Cond,
8836                 Then_Statements => New_List (
8837                   Make_Assignment_Statement (Loc,
8838                     Name       => New_Reference_To (Delay_Min, Loc),
8839                     Expression => New_Reference_To (Delay_Val, Loc)),
8840
8841                   Make_Assignment_Statement (Loc,
8842                     Name       => New_Reference_To (Delay_Index, Loc),
8843                     Expression => Make_Integer_Literal (Loc, Index)))));
8844          end if;
8845
8846          if Check_Guard then
8847             Append_To (Delay_Alt,
8848               Make_Assignment_Statement (Loc,
8849                 Name => New_Reference_To (Guard_Open, Loc),
8850                 Expression => New_Reference_To (Standard_True, Loc)));
8851          end if;
8852
8853          if Present (Condition (Alt)) then
8854             Delay_Alt := New_List (
8855               Make_Implicit_If_Statement (N,
8856                 Condition => Condition (Alt),
8857                 Then_Statements => Delay_Alt));
8858          end if;
8859
8860          Append_List (Delay_Alt, Delay_List);
8861
8862          --  If the delay alternative has a statement part, add choice to the
8863          --  case statements for delays.
8864
8865          if Present (Statements (Alt)) then
8866
8867             if Delay_Count = 1 then
8868                Append_List (Statements (Alt), Delay_Alt_List);
8869
8870             else
8871                Choices := New_List (
8872                  Make_Integer_Literal (Loc, Index));
8873
8874                Append_To (Delay_Alt_List,
8875                  Make_Case_Statement_Alternative (Loc,
8876                    Discrete_Choices => Choices,
8877                    Statements => Statements (Alt)));
8878             end if;
8879
8880          elsif Delay_Count = 1 then
8881
8882             --  If the single delay has no trailing statements, add a branch
8883             --  to the exit label to the selective wait.
8884
8885             Delay_Alt_List := New_List (
8886               Make_Goto_Statement (Loc,
8887                 Name => New_Copy (Identifier (End_Lab))));
8888
8889          end if;
8890       end Process_Delay_Alternative;
8891
8892    --  Start of processing for Expand_N_Selective_Accept
8893
8894    begin
8895       --  First insert some declarations before the select. The first is:
8896
8897       --    Ann : Address
8898
8899       --  This variable holds the parameters passed to the accept body. This
8900       --  declaration has already been inserted by the time we get here by
8901       --  a call to Expand_Accept_Declarations made from the semantics when
8902       --  processing the first accept statement contained in the select. We
8903       --  can find this entity as Accept_Address (E), where E is any of the
8904       --  entries references by contained accept statements.
8905
8906       --  The first step is to scan the list of Selective_Accept_Statements
8907       --  to find this entity, and also count the number of accepts, and
8908       --  determine if terminated, delay or else is present:
8909
8910       Num_Alts := 0;
8911
8912       Alt := First (Alts);
8913       while Present (Alt) loop
8914
8915          if Nkind (Alt) = N_Accept_Alternative then
8916             Add_Accept (Alt);
8917
8918          elsif Nkind (Alt) = N_Delay_Alternative then
8919             Delay_Count := Delay_Count + 1;
8920
8921             --  If the delays are relative delays, the delay expressions have
8922             --  type Standard_Duration. Otherwise they must have some time type
8923             --  recognized by GNAT.
8924
8925             if Nkind (Delay_Statement (Alt)) = N_Delay_Relative_Statement then
8926                Time_Type := Standard_Duration;
8927             else
8928                Time_Type := Etype (Expression (Delay_Statement (Alt)));
8929
8930                if Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time)
8931                  or else Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time)
8932                then
8933                   null;
8934                else
8935                   Error_Msg_NE (
8936                     "& is not a time type (RM 9.6(6))",
8937                        Expression (Delay_Statement (Alt)), Time_Type);
8938                   Time_Type := Standard_Duration;
8939                   Set_Etype (Expression (Delay_Statement (Alt)), Any_Type);
8940                end if;
8941             end if;
8942
8943             if No (Condition (Alt)) then
8944
8945                --  This guard will always be open
8946
8947                Check_Guard := False;
8948             end if;
8949
8950          elsif Nkind (Alt) = N_Terminate_Alternative then
8951             Adjust_Condition (Condition (Alt));
8952             Terminate_Alt := Alt;
8953          end if;
8954
8955          Num_Alts := Num_Alts + 1;
8956          Next (Alt);
8957       end loop;
8958
8959       Else_Present := Present (Else_Statements (N));
8960
8961       --  At the same time (see procedure Add_Accept) we build the accept list:
8962
8963       --    Qnn : Accept_List (1 .. num-select) := (
8964       --          (null-body, entry-index),
8965       --          (null-body, entry-index),
8966       --          ..
8967       --          (null_body, entry-index));
8968
8969       --  In the above declaration, null-body is True if the corresponding
8970       --  accept has no body, and false otherwise. The entry is either the
8971       --  entry index expression if there is no guard, or if a guard is
8972       --  present, then a conditional expression of the form:
8973
8974       --    (if guard then entry-index else Null_Task_Entry)
8975
8976       --  If a guard is statically known to be false, the entry can simply
8977       --  be omitted from the accept list.
8978
8979       Q :=
8980         Make_Object_Declaration (Loc,
8981           Defining_Identifier => Qnam,
8982           Object_Definition =>
8983             New_Reference_To (RTE (RE_Accept_List), Loc),
8984           Aliased_Present => True,
8985
8986           Expression =>
8987              Make_Qualified_Expression (Loc,
8988                Subtype_Mark =>
8989                  New_Reference_To (RTE (RE_Accept_List), Loc),
8990                Expression =>
8991                  Make_Aggregate (Loc, Expressions => Accept_List)));
8992
8993       Append (Q, Decls);
8994
8995       --  Then we declare the variable that holds the index for the accept
8996       --  that will be selected for service:
8997
8998       --    Xnn : Select_Index;
8999
9000       X :=
9001         Make_Object_Declaration (Loc,
9002           Defining_Identifier => Xnam,
9003           Object_Definition =>
9004             New_Reference_To (RTE (RE_Select_Index), Loc),
9005           Expression =>
9006             New_Reference_To (RTE (RE_No_Rendezvous), Loc));
9007
9008       Append (X, Decls);
9009
9010       --  After this follow procedure declarations for each accept body
9011
9012       --    procedure Pnn is
9013       --    begin
9014       --       ...
9015       --    end;
9016
9017       --  where the ... are statements from the corresponding procedure body.
9018       --  No parameters are involved, since the parameters are passed via Ann
9019       --  and the parameter references have already been expanded to be direct
9020       --  references to Ann (see Exp_Ch2.Expand_Entry_Parameter). Furthermore,
9021       --  any embedded tasking statements (which would normally be illegal in
9022       --  procedures), have been converted to calls to the tasking runtime so
9023       --  there is no problem in putting them into procedures.
9024
9025       --  The original accept statement has been expanded into a block in
9026       --  the same fashion as for simple accepts (see Build_Accept_Body).
9027
9028       --  Note: we don't really need to build these procedures for the case
9029       --  where no delay statement is present, but it is just as easy to
9030       --  build them unconditionally, and not significantly inefficient,
9031       --  since if they are short they will be inlined anyway.
9032
9033       --  The procedure declarations have been assembled in Body_List
9034
9035       --  If delays are present, we must compute the required delay.
9036       --  We first generate the declarations:
9037
9038       --    Delay_Index : Boolean := 0;
9039       --    Delay_Min   : Some_Time_Type.Time;
9040       --    Delay_Val   : Some_Time_Type.Time;
9041
9042       --  Delay_Index will be set to the index of the minimum delay, i.e. the
9043       --  active delay that is actually chosen as the basis for the possible
9044       --  delay if an immediate rendez-vous is not possible.
9045
9046       --  In the most common case there is a single delay statement, and this
9047       --  is handled specially.
9048
9049       if Delay_Count > 0 then
9050
9051          --  Generate the required declarations
9052
9053          Delay_Val :=
9054            Make_Defining_Identifier (Loc, New_External_Name ('D', 1));
9055          Delay_Index :=
9056            Make_Defining_Identifier (Loc, New_External_Name ('D', 2));
9057          Delay_Min :=
9058            Make_Defining_Identifier (Loc, New_External_Name ('D', 3));
9059
9060          Append_To (Decls,
9061            Make_Object_Declaration (Loc,
9062              Defining_Identifier => Delay_Val,
9063              Object_Definition   => New_Reference_To (Time_Type, Loc)));
9064
9065          Append_To (Decls,
9066            Make_Object_Declaration (Loc,
9067              Defining_Identifier => Delay_Index,
9068              Object_Definition   => New_Reference_To (Standard_Integer, Loc),
9069              Expression          => Make_Integer_Literal (Loc, 0)));
9070
9071          Append_To (Decls,
9072            Make_Object_Declaration (Loc,
9073              Defining_Identifier => Delay_Min,
9074              Object_Definition   => New_Reference_To (Time_Type, Loc),
9075              Expression          =>
9076                Unchecked_Convert_To (Time_Type,
9077                  Make_Attribute_Reference (Loc,
9078                    Prefix =>
9079                      New_Occurrence_Of (Underlying_Type (Time_Type), Loc),
9080                    Attribute_Name => Name_Last))));
9081
9082          --  Create Duration and Delay_Mode objects used for passing a delay
9083          --  value to RTS
9084
9085          D := Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
9086          M := Make_Defining_Identifier (Loc, New_Internal_Name ('M'));
9087
9088          declare
9089             Discr : Entity_Id;
9090
9091          begin
9092             --  Note that these values are defined in s-osprim.ads and must
9093             --  be kept in sync:
9094             --
9095             --     Relative          : constant := 0;
9096             --     Absolute_Calendar : constant := 1;
9097             --     Absolute_RT       : constant := 2;
9098
9099             if Time_Type = Standard_Duration then
9100                Discr := Make_Integer_Literal (Loc, 0);
9101
9102             elsif Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time) then
9103                Discr := Make_Integer_Literal (Loc, 1);
9104
9105             else
9106                pragma Assert
9107                  (Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time));
9108                Discr := Make_Integer_Literal (Loc, 2);
9109             end if;
9110
9111             Append_To (Decls,
9112               Make_Object_Declaration (Loc,
9113                 Defining_Identifier => D,
9114                 Object_Definition =>
9115                   New_Reference_To (Standard_Duration, Loc)));
9116
9117             Append_To (Decls,
9118               Make_Object_Declaration (Loc,
9119                 Defining_Identifier => M,
9120                 Object_Definition   =>
9121                   New_Reference_To (Standard_Integer, Loc),
9122                 Expression          => Discr));
9123          end;
9124
9125          if Check_Guard then
9126             Guard_Open :=
9127               Make_Defining_Identifier (Loc, New_External_Name ('G', 1));
9128
9129             Append_To (Decls,
9130               Make_Object_Declaration (Loc,
9131                  Defining_Identifier => Guard_Open,
9132                  Object_Definition => New_Reference_To (Standard_Boolean, Loc),
9133                  Expression        => New_Reference_To (Standard_False, Loc)));
9134          end if;
9135
9136       --  Delay_Count is zero, don't need M and D set (suppress warning)
9137
9138       else
9139          M := Empty;
9140          D := Empty;
9141       end if;
9142
9143       if Present (Terminate_Alt) then
9144
9145          --  If the terminate alternative guard is False, use
9146          --  Simple_Mode; otherwise use Terminate_Mode.
9147
9148          if Present (Condition (Terminate_Alt)) then
9149             Select_Mode := Make_Conditional_Expression (Loc,
9150               New_List (Condition (Terminate_Alt),
9151                         New_Reference_To (RTE (RE_Terminate_Mode), Loc),
9152                         New_Reference_To (RTE (RE_Simple_Mode), Loc)));
9153          else
9154             Select_Mode := New_Reference_To (RTE (RE_Terminate_Mode), Loc);
9155          end if;
9156
9157       elsif Else_Present or Delay_Count > 0 then
9158          Select_Mode := New_Reference_To (RTE (RE_Else_Mode), Loc);
9159
9160       else
9161          Select_Mode := New_Reference_To (RTE (RE_Simple_Mode), Loc);
9162       end if;
9163
9164       Select_Call := Make_Select_Call (Select_Mode);
9165       Append (Select_Call, Stats);
9166
9167       --  Now generate code to act on the result. There is an entry
9168       --  in this case for each accept statement with a non-null body,
9169       --  followed by a branch to the statements that follow the Accept.
9170       --  In the absence of delay alternatives, we generate:
9171
9172       --    case X is
9173       --      when No_Rendezvous =>  --  omitted if simple mode
9174       --         goto Lab0;
9175
9176       --      when 1 =>
9177       --         P1n;
9178       --         goto Lab1;
9179
9180       --      when 2 =>
9181       --         P2n;
9182       --         goto Lab2;
9183
9184       --      when others =>
9185       --         goto Exit;
9186       --    end case;
9187       --
9188       --    Lab0: Else_Statements;
9189       --    goto exit;
9190
9191       --    Lab1:  Trailing_Statements1;
9192       --    goto Exit;
9193       --
9194       --    Lab2:  Trailing_Statements2;
9195       --    goto Exit;
9196       --    ...
9197       --    Exit:
9198
9199       --  Generate label for common exit
9200
9201       End_Lab := Make_And_Declare_Label (Num_Alts + 1);
9202
9203       --  First entry is the default case, when no rendezvous is possible
9204
9205       Choices := New_List (New_Reference_To (RTE (RE_No_Rendezvous), Loc));
9206
9207       if Else_Present then
9208
9209          --  If no rendezvous is possible, the else part is executed
9210
9211          Lab := Make_And_Declare_Label (0);
9212          Alt_Stats := New_List (
9213            Make_Goto_Statement (Loc,
9214              Name => New_Copy (Identifier (Lab))));
9215
9216          Append (Lab, Trailing_List);
9217          Append_List (Else_Statements (N), Trailing_List);
9218          Append_To (Trailing_List,
9219            Make_Goto_Statement (Loc,
9220              Name => New_Copy (Identifier (End_Lab))));
9221       else
9222          Alt_Stats := New_List (
9223            Make_Goto_Statement (Loc,
9224              Name => New_Copy (Identifier (End_Lab))));
9225       end if;
9226
9227       Append_To (Alt_List,
9228         Make_Case_Statement_Alternative (Loc,
9229           Discrete_Choices => Choices,
9230           Statements => Alt_Stats));
9231
9232       --  We make use of the fact that Accept_Index is an integer type, and
9233       --  generate successive literals for entries for each accept. Only those
9234       --  for which there is a body or trailing statements get a case entry.
9235
9236       Alt := First (Select_Alternatives (N));
9237       Proc := First (Body_List);
9238       while Present (Alt) loop
9239
9240          if Nkind (Alt) = N_Accept_Alternative then
9241             Process_Accept_Alternative (Alt, Index, Proc);
9242             Index := Index + 1;
9243
9244             if Present
9245               (Handled_Statement_Sequence (Accept_Statement (Alt)))
9246             then
9247                Next (Proc);
9248             end if;
9249
9250          elsif Nkind (Alt) = N_Delay_Alternative then
9251             Process_Delay_Alternative (Alt, Delay_Num);
9252             Delay_Num := Delay_Num + 1;
9253          end if;
9254
9255          Next (Alt);
9256       end loop;
9257
9258       --  An others choice is always added to the main case, as well
9259       --  as the delay case (to satisfy the compiler).
9260
9261       Append_To (Alt_List,
9262         Make_Case_Statement_Alternative (Loc,
9263           Discrete_Choices =>
9264             New_List (Make_Others_Choice (Loc)),
9265           Statements       =>
9266             New_List (Make_Goto_Statement (Loc,
9267               Name => New_Copy (Identifier (End_Lab))))));
9268
9269       Accept_Case := New_List (
9270         Make_Case_Statement (Loc,
9271           Expression   => New_Reference_To (Xnam, Loc),
9272           Alternatives => Alt_List));
9273
9274       Append_List (Trailing_List, Accept_Case);
9275       Append (End_Lab, Accept_Case);
9276       Append_List (Body_List, Decls);
9277
9278       --  Construct case statement for trailing statements of delay
9279       --  alternatives, if there are several of them.
9280
9281       if Delay_Count > 1 then
9282          Append_To (Delay_Alt_List,
9283            Make_Case_Statement_Alternative (Loc,
9284              Discrete_Choices =>
9285                New_List (Make_Others_Choice (Loc)),
9286              Statements       =>
9287                New_List (Make_Null_Statement (Loc))));
9288
9289          Delay_Case := New_List (
9290            Make_Case_Statement (Loc,
9291              Expression   => New_Reference_To (Delay_Index, Loc),
9292              Alternatives => Delay_Alt_List));
9293       else
9294          Delay_Case := Delay_Alt_List;
9295       end if;
9296
9297       --  If there are no delay alternatives, we append the case statement
9298       --  to the statement list.
9299
9300       if Delay_Count = 0 then
9301          Append_List (Accept_Case, Stats);
9302
9303       --  Delay alternatives present
9304
9305       else
9306          --  If delay alternatives are present we generate:
9307
9308          --    find minimum delay.
9309          --    DX := minimum delay;
9310          --    M := <delay mode>;
9311          --    Timed_Selective_Wait (Q'Unchecked_Access, Delay_Mode, P,
9312          --      DX, MX, X);
9313          --
9314          --    if X = No_Rendezvous then
9315          --      case statement for delay statements.
9316          --    else
9317          --      case statement for accept alternatives.
9318          --    end if;
9319
9320          declare
9321             Cases : Node_Id;
9322             Stmt  : Node_Id;
9323             Parms : List_Id;
9324             Parm  : Node_Id;
9325             Conv  : Node_Id;
9326
9327          begin
9328             --  The type of the delay expression is known to be legal
9329
9330             if Time_Type = Standard_Duration then
9331                Conv := New_Reference_To (Delay_Min, Loc);
9332
9333             elsif Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time) then
9334                Conv := Make_Function_Call (Loc,
9335                  New_Reference_To (RTE (RO_CA_To_Duration), Loc),
9336                  New_List (New_Reference_To (Delay_Min, Loc)));
9337
9338             else
9339                pragma Assert
9340                  (Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time));
9341
9342                Conv := Make_Function_Call (Loc,
9343                  New_Reference_To (RTE (RO_RT_To_Duration), Loc),
9344                  New_List (New_Reference_To (Delay_Min, Loc)));
9345             end if;
9346
9347             Stmt := Make_Assignment_Statement (Loc,
9348               Name => New_Reference_To (D, Loc),
9349               Expression => Conv);
9350
9351             --  Change the value for Accept_Modes. (Else_Mode -> Delay_Mode)
9352
9353             Parms := Parameter_Associations (Select_Call);
9354             Parm := First (Parms);
9355
9356             while Present (Parm)
9357               and then Parm /= Select_Mode
9358             loop
9359                Next (Parm);
9360             end loop;
9361
9362             pragma Assert (Present (Parm));
9363             Rewrite (Parm, New_Reference_To (RTE (RE_Delay_Mode), Loc));
9364             Analyze (Parm);
9365
9366             --  Prepare two new parameters of Duration and Delay_Mode type
9367             --  which represent the value and the mode of the minimum delay.
9368
9369             Next (Parm);
9370             Insert_After (Parm, New_Reference_To (M, Loc));
9371             Insert_After (Parm, New_Reference_To (D, Loc));
9372
9373             --  Create a call to RTS
9374
9375             Rewrite (Select_Call,
9376               Make_Procedure_Call_Statement (Loc,
9377                 Name => New_Reference_To (RTE (RE_Timed_Selective_Wait), Loc),
9378                 Parameter_Associations => Parms));
9379
9380             --  This new call should follow the calculation of the minimum
9381             --  delay.
9382
9383             Insert_List_Before (Select_Call, Delay_List);
9384
9385             if Check_Guard then
9386                Stmt :=
9387                  Make_Implicit_If_Statement (N,
9388                    Condition => New_Reference_To (Guard_Open, Loc),
9389                    Then_Statements =>
9390                      New_List (New_Copy_Tree (Stmt),
9391                        New_Copy_Tree (Select_Call)),
9392                    Else_Statements => Accept_Or_Raise);
9393                Rewrite (Select_Call, Stmt);
9394             else
9395                Insert_Before (Select_Call, Stmt);
9396             end if;
9397
9398             Cases :=
9399               Make_Implicit_If_Statement (N,
9400                 Condition => Make_Op_Eq (Loc,
9401                   Left_Opnd  => New_Reference_To (Xnam, Loc),
9402                   Right_Opnd =>
9403                     New_Reference_To (RTE (RE_No_Rendezvous), Loc)),
9404
9405                 Then_Statements => Delay_Case,
9406                 Else_Statements => Accept_Case);
9407
9408             Append (Cases, Stats);
9409          end;
9410       end if;
9411
9412       --  Replace accept statement with appropriate block
9413
9414       Block :=
9415         Make_Block_Statement (Loc,
9416           Declarations => Decls,
9417           Handled_Statement_Sequence =>
9418             Make_Handled_Sequence_Of_Statements (Loc,
9419               Statements => Stats));
9420
9421       Rewrite (N, Block);
9422       Analyze (N);
9423
9424       --  Note: have to worry more about abort deferral in above code ???
9425
9426       --  Final step is to unstack the Accept_Address entries for all accept
9427       --  statements appearing in accept alternatives in the select statement
9428
9429       Alt := First (Alts);
9430       while Present (Alt) loop
9431          if Nkind (Alt) = N_Accept_Alternative then
9432             Remove_Last_Elmt (Accept_Address
9433               (Entity (Entry_Direct_Name (Accept_Statement (Alt)))));
9434          end if;
9435
9436          Next (Alt);
9437       end loop;
9438    end Expand_N_Selective_Accept;
9439
9440    --------------------------------------
9441    -- Expand_N_Single_Task_Declaration --
9442    --------------------------------------
9443
9444    --  Single task declarations should never be present after semantic
9445    --  analysis, since we expect them to be replaced by a declaration of an
9446    --  anonymous task type, followed by a declaration of the task object. We
9447    --  include this routine to make sure that is happening!
9448
9449    procedure Expand_N_Single_Task_Declaration (N : Node_Id) is
9450    begin
9451       raise Program_Error;
9452    end Expand_N_Single_Task_Declaration;
9453
9454    ------------------------
9455    -- Expand_N_Task_Body --
9456    ------------------------
9457
9458    --  Given a task body
9459
9460    --    task body tname is
9461    --       <declarations>
9462    --    begin
9463    --       <statements>
9464    --    end x;
9465
9466    --  This expansion routine converts it into a procedure and sets the
9467    --  elaboration flag for the procedure to true, to represent the fact
9468    --  that the task body is now elaborated:
9469
9470    --    procedure tnameB (_Task : access tnameV) is
9471    --       discriminal : dtype renames _Task.discriminant;
9472
9473    --       procedure _clean is
9474    --       begin
9475    --          Abort_Defer.all;
9476    --          Complete_Task;
9477    --          Abort_Undefer.all;
9478    --          return;
9479    --       end _clean;
9480
9481    --    begin
9482    --       Abort_Undefer.all;
9483    --       <declarations>
9484    --       System.Task_Stages.Complete_Activation;
9485    --       <statements>
9486    --    at end
9487    --       _clean;
9488    --    end tnameB;
9489
9490    --    tnameE := True;
9491
9492    --  In addition, if the task body is an activator, then a call to activate
9493    --  tasks is added at the start of the statements, before the call to
9494    --  Complete_Activation, and if in addition the task is a master then it
9495    --  must be established as a master. These calls are inserted and analyzed
9496    --  in Expand_Cleanup_Actions, when the Handled_Sequence_Of_Statements is
9497    --  expanded.
9498
9499    --  There is one discriminal declaration line generated for each
9500    --  discriminant that is present to provide an easy reference point for
9501    --  discriminant references inside the body (see Exp_Ch2.Expand_Name).
9502
9503    --  Note on relationship to GNARLI definition. In the GNARLI definition,
9504    --  task body procedures have a profile (Arg : System.Address). That is
9505    --  needed because GNARLI has to use the same access-to-subprogram type
9506    --  for all task types. We depend here on knowing that in GNAT, passing
9507    --  an address argument by value is identical to passing a record value
9508    --  by access (in either case a single pointer is passed), so even though
9509    --  this procedure has the wrong profile. In fact it's all OK, since the
9510    --  callings sequence is identical.
9511
9512    procedure Expand_N_Task_Body (N : Node_Id) is
9513       Loc   : constant Source_Ptr := Sloc (N);
9514       Ttyp  : constant Entity_Id  := Corresponding_Spec (N);
9515       Call  : Node_Id;
9516       New_N : Node_Id;
9517
9518       Insert_Nod : Node_Id;
9519       --  Used to determine the proper location of wrapper body insertions
9520
9521    begin
9522       --  Add renaming declarations for discriminals and a declaration for the
9523       --  entry family index (if applicable).
9524
9525       Install_Private_Data_Declarations
9526         (Loc, Task_Body_Procedure (Ttyp), Ttyp, N, Declarations (N));
9527
9528       --  Add a call to Abort_Undefer at the very beginning of the task
9529       --  body since this body is called with abort still deferred.
9530
9531       if Abort_Allowed then
9532          Call := Build_Runtime_Call (Loc, RE_Abort_Undefer);
9533          Insert_Before
9534            (First (Statements (Handled_Statement_Sequence (N))), Call);
9535          Analyze (Call);
9536       end if;
9537
9538       --  The statement part has already been protected with an at_end and
9539       --  cleanup actions. The call to Complete_Activation must be placed
9540       --  at the head of the sequence of statements of that block. The
9541       --  declarations have been merged in this sequence of statements but
9542       --  the first real statement is accessible from the First_Real_Statement
9543       --  field (which was set for exactly this purpose).
9544
9545       if Restricted_Profile then
9546          Call := Build_Runtime_Call (Loc, RE_Complete_Restricted_Activation);
9547       else
9548          Call := Build_Runtime_Call (Loc, RE_Complete_Activation);
9549       end if;
9550
9551       Insert_Before
9552         (First_Real_Statement (Handled_Statement_Sequence (N)), Call);
9553       Analyze (Call);
9554
9555       New_N :=
9556         Make_Subprogram_Body (Loc,
9557           Specification              => Build_Task_Proc_Specification (Ttyp),
9558           Declarations               => Declarations (N),
9559           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
9560
9561       --  If the task contains generic instantiations, cleanup actions are
9562       --  delayed until after instantiation. Transfer the activation chain to
9563       --  the subprogram, to insure that the activation call is properly
9564       --  generated. It the task body contains inner tasks, indicate that the
9565       --  subprogram is a task master.
9566
9567       if Delay_Cleanups (Ttyp) then
9568          Set_Activation_Chain_Entity (New_N, Activation_Chain_Entity (N));
9569          Set_Is_Task_Master  (New_N, Is_Task_Master (N));
9570       end if;
9571
9572       Rewrite (N, New_N);
9573       Analyze (N);
9574
9575       --  Set elaboration flag immediately after task body. If the body is a
9576       --  subunit, the flag is set in the declarative part containing the stub.
9577
9578       if Nkind (Parent (N)) /= N_Subunit then
9579          Insert_After (N,
9580            Make_Assignment_Statement (Loc,
9581              Name =>
9582                Make_Identifier (Loc, New_External_Name (Chars (Ttyp), 'E')),
9583              Expression => New_Reference_To (Standard_True, Loc)));
9584       end if;
9585
9586       --  Ada 2005 (AI-345): Construct the primitive entry wrapper bodies after
9587       --  the task body. At this point all wrapper specs have been created,
9588       --  frozen and included in the dispatch table for the task type.
9589
9590       if Ada_Version >= Ada_05 then
9591          if Nkind (Parent (N)) = N_Subunit then
9592             Insert_Nod := Corresponding_Stub (Parent (N));
9593          else
9594             Insert_Nod := N;
9595          end if;
9596
9597          Build_Wrapper_Bodies (Loc, Ttyp, Insert_Nod);
9598       end if;
9599    end Expand_N_Task_Body;
9600
9601    ------------------------------------
9602    -- Expand_N_Task_Type_Declaration --
9603    ------------------------------------
9604
9605    --  We have several things to do. First we must create a Boolean flag used
9606    --  to mark if the body is elaborated yet. This variable gets set to True
9607    --  when the body of the task is elaborated (we can't rely on the normal
9608    --  ABE mechanism for the task body, since we need to pass an access to
9609    --  this elaboration boolean to the runtime routines).
9610
9611    --    taskE : aliased Boolean := False;
9612
9613    --  Next a variable is declared to hold the task stack size (either the
9614    --  default : Unspecified_Size, or a value that is set by a pragma
9615    --  Storage_Size). If the value of the pragma Storage_Size is static, then
9616    --  the variable is initialized with this value:
9617
9618    --    taskZ : Size_Type := Unspecified_Size;
9619    --  or
9620    --    taskZ : Size_Type := Size_Type (size_expression);
9621
9622    --  Note: No variable is needed to hold the task relative deadline since
9623    --  its value would never be static because the parameter is of a private
9624    --  type (Ada.Real_Time.Time_Span).
9625
9626    --  Next we create a corresponding record type declaration used to represent
9627    --  values of this task. The general form of this type declaration is
9628
9629    --    type taskV (discriminants) is record
9630    --      _Task_Id     : Task_Id;
9631    --      entry_family : array (bounds) of Void;
9632    --      _Priority    : Integer         := priority_expression;
9633    --      _Size        : Size_Type       := Size_Type (size_expression);
9634    --      _Task_Info   : Task_Info_Type  := task_info_expression;
9635    --    end record;
9636
9637    --  The discriminants are present only if the corresponding task type has
9638    --  discriminants, and they exactly mirror the task type discriminants.
9639
9640    --  The Id field is always present. It contains the Task_Id value, as set by
9641    --  the call to Create_Task. Note that although the task is limited, the
9642    --  task value record type is not limited, so there is no problem in passing
9643    --  this field as an out parameter to Create_Task.
9644
9645    --  One entry_family component is present for each entry family in the task
9646    --  definition. The bounds correspond to the bounds of the entry family
9647    --  (which may depend on discriminants). The element type is void, since we
9648    --  only need the bounds information for determining the entry index. Note
9649    --  that the use of an anonymous array would normally be illegal in this
9650    --  context, but this is a parser check, and the semantics is quite prepared
9651    --  to handle such a case.
9652
9653    --  The _Size field is present only if a Storage_Size pragma appears in the
9654    --  task definition. The expression captures the argument that was present
9655    --  in the pragma, and is used to override the task stack size otherwise
9656    --  associated with the task type.
9657
9658    --  The _Priority field is present only if a Priority or Interrupt_Priority
9659    --  pragma appears in the task definition. The expression captures the
9660    --  argument that was present in the pragma, and is used to provide the Size
9661    --  parameter to the call to Create_Task.
9662
9663    --  The _Task_Info field is present only if a Task_Info pragma appears in
9664    --  the task definition. The expression captures the argument that was
9665    --  present in the pragma, and is used to provide the Task_Image parameter
9666    --  to the call to Create_Task.
9667
9668    --  The _Relative_Deadline field is present only if a Relative_Deadline
9669    --  pragma appears in the task definition. The expression captures the
9670    --  argument that was present in the pragma, and is used to provide the
9671    --  Relative_Deadline parameter to the call to Create_Task.
9672
9673    --  When a task is declared, an instance of the task value record is
9674    --  created. The elaboration of this declaration creates the correct bounds
9675    --  for the entry families, and also evaluates the size, priority, and
9676    --  task_Info expressions if needed. The initialization routine for the task
9677    --  type itself then calls Create_Task with appropriate parameters to
9678    --  initialize the value of the Task_Id field.
9679
9680    --  Note: the address of this record is passed as the "Discriminants"
9681    --  parameter for Create_Task. Since Create_Task merely passes this onto the
9682    --  body procedure, it does not matter that it does not quite match the
9683    --  GNARLI model of what is being passed (the record contains more than just
9684    --  the discriminants, but the discriminants can be found from the record
9685    --  value).
9686
9687    --  The Entity_Id for this created record type is placed in the
9688    --  Corresponding_Record_Type field of the associated task type entity.
9689
9690    --  Next we create a procedure specification for the task body procedure:
9691
9692    --    procedure taskB (_Task : access taskV);
9693
9694    --  Note that this must come after the record type declaration, since
9695    --  the spec refers to this type. It turns out that the initialization
9696    --  procedure for the value type references the task body spec, but that's
9697    --  fine, since it won't be generated till the freeze point for the type,
9698    --  which is certainly after the task body spec declaration.
9699
9700    --  Finally, we set the task index value field of the entry attribute in
9701    --  the case of a simple entry.
9702
9703    procedure Expand_N_Task_Type_Declaration (N : Node_Id) is
9704       Loc     : constant Source_Ptr := Sloc (N);
9705       Tasktyp : constant Entity_Id  := Etype (Defining_Identifier (N));
9706       Tasknm  : constant Name_Id    := Chars (Tasktyp);
9707       Taskdef : constant Node_Id    := Task_Definition (N);
9708
9709       Proc_Spec  : Node_Id;
9710       Rec_Decl   : Node_Id;
9711       Rec_Ent    : Entity_Id;
9712       Cdecls     : List_Id;
9713       Elab_Decl  : Node_Id;
9714       Size_Decl  : Node_Id;
9715       Body_Decl  : Node_Id;
9716       Task_Size  : Node_Id;
9717       Ent_Stack  : Entity_Id;
9718       Decl_Stack : Node_Id;
9719
9720    begin
9721       --  If already expanded, nothing to do
9722
9723       if Present (Corresponding_Record_Type (Tasktyp)) then
9724          return;
9725       end if;
9726
9727       --  Here we will do the expansion
9728
9729       Rec_Decl := Build_Corresponding_Record (N, Tasktyp, Loc);
9730
9731       --  Ada 2005 (AI-345): Propagate the attribute that contains the list
9732       --  of implemented interfaces.
9733
9734       Set_Interface_List (Type_Definition (Rec_Decl), Interface_List (N));
9735
9736       Rec_Ent  := Defining_Identifier (Rec_Decl);
9737       Cdecls   := Component_Items (Component_List
9738                                      (Type_Definition (Rec_Decl)));
9739
9740       Qualify_Entity_Names (N);
9741
9742       --  First create the elaboration variable
9743
9744       Elab_Decl :=
9745         Make_Object_Declaration (Loc,
9746           Defining_Identifier =>
9747             Make_Defining_Identifier (Sloc (Tasktyp),
9748               Chars => New_External_Name (Tasknm, 'E')),
9749           Aliased_Present      => True,
9750           Object_Definition    => New_Reference_To (Standard_Boolean, Loc),
9751           Expression           => New_Reference_To (Standard_False, Loc));
9752       Insert_After (N, Elab_Decl);
9753
9754       --  Next create the declaration of the size variable (tasknmZ)
9755
9756       Set_Storage_Size_Variable (Tasktyp,
9757         Make_Defining_Identifier (Sloc (Tasktyp),
9758           Chars => New_External_Name (Tasknm, 'Z')));
9759
9760       if Present (Taskdef) and then Has_Storage_Size_Pragma (Taskdef) and then
9761         Is_Static_Expression (Expression (First (
9762           Pragma_Argument_Associations (Find_Task_Or_Protected_Pragma (
9763             Taskdef, Name_Storage_Size)))))
9764       then
9765          Size_Decl :=
9766            Make_Object_Declaration (Loc,
9767              Defining_Identifier => Storage_Size_Variable (Tasktyp),
9768              Object_Definition => New_Reference_To (RTE (RE_Size_Type), Loc),
9769              Expression =>
9770                Convert_To (RTE (RE_Size_Type),
9771                  Relocate_Node (
9772                    Expression (First (
9773                      Pragma_Argument_Associations (
9774                        Find_Task_Or_Protected_Pragma
9775                          (Taskdef, Name_Storage_Size)))))));
9776
9777       else
9778          Size_Decl :=
9779            Make_Object_Declaration (Loc,
9780              Defining_Identifier => Storage_Size_Variable (Tasktyp),
9781              Object_Definition => New_Reference_To (RTE (RE_Size_Type), Loc),
9782              Expression => New_Reference_To (RTE (RE_Unspecified_Size), Loc));
9783       end if;
9784
9785       Insert_After (Elab_Decl, Size_Decl);
9786
9787       --  Next build the rest of the corresponding record declaration. This is
9788       --  done last, since the corresponding record initialization procedure
9789       --  will reference the previously created entities.
9790
9791       --  Fill in the component declarations -- first the _Task_Id field
9792
9793       Append_To (Cdecls,
9794         Make_Component_Declaration (Loc,
9795           Defining_Identifier =>
9796             Make_Defining_Identifier (Loc, Name_uTask_Id),
9797           Component_Definition =>
9798             Make_Component_Definition (Loc,
9799               Aliased_Present    => False,
9800               Subtype_Indication => New_Reference_To (RTE (RO_ST_Task_Id),
9801                                     Loc))));
9802
9803       --  Declare static ATCB (that is, created by the expander) if we are
9804       --  using the Restricted run time.
9805
9806       if Restricted_Profile then
9807          Append_To (Cdecls,
9808            Make_Component_Declaration (Loc,
9809              Defining_Identifier  =>
9810                Make_Defining_Identifier (Loc, Name_uATCB),
9811
9812              Component_Definition =>
9813                Make_Component_Definition (Loc,
9814                  Aliased_Present     => True,
9815                  Subtype_Indication  => Make_Subtype_Indication (Loc,
9816                    Subtype_Mark => New_Occurrence_Of
9817                      (RTE (RE_Ada_Task_Control_Block), Loc),
9818
9819                    Constraint   =>
9820                      Make_Index_Or_Discriminant_Constraint (Loc,
9821                        Constraints =>
9822                          New_List (Make_Integer_Literal (Loc, 0)))))));
9823
9824       end if;
9825
9826       --  Declare static stack (that is, created by the expander) if we are
9827       --  using the Restricted run time on a bare board configuration.
9828
9829       if Restricted_Profile
9830         and then Preallocated_Stacks_On_Target
9831       then
9832          --  First we need to extract the appropriate stack size
9833
9834          Ent_Stack := Make_Defining_Identifier (Loc, Name_uStack);
9835
9836          if Present (Taskdef) and then Has_Storage_Size_Pragma (Taskdef) then
9837             declare
9838                Expr_N : constant Node_Id :=
9839                           Expression (First (
9840                             Pragma_Argument_Associations (
9841                               Find_Task_Or_Protected_Pragma
9842                                 (Taskdef, Name_Storage_Size))));
9843                Etyp   : constant Entity_Id := Etype (Expr_N);
9844                P      : constant Node_Id   := Parent (Expr_N);
9845
9846             begin
9847                --  The stack is defined inside the corresponding record.
9848                --  Therefore if the size of the stack is set by means of
9849                --  a discriminant, we must reference the discriminant of the
9850                --  corresponding record type.
9851
9852                if Nkind (Expr_N) in N_Has_Entity
9853                  and then Present (Discriminal_Link (Entity (Expr_N)))
9854                then
9855                   Task_Size :=
9856                     New_Reference_To
9857                       (CR_Discriminant (Discriminal_Link (Entity (Expr_N))),
9858                        Loc);
9859                   Set_Parent   (Task_Size, P);
9860                   Set_Etype    (Task_Size, Etyp);
9861                   Set_Analyzed (Task_Size);
9862
9863                else
9864                   Task_Size := Relocate_Node (Expr_N);
9865                end if;
9866             end;
9867
9868          else
9869             Task_Size :=
9870               New_Reference_To (RTE (RE_Default_Stack_Size), Loc);
9871          end if;
9872
9873          Decl_Stack := Make_Component_Declaration (Loc,
9874            Defining_Identifier  => Ent_Stack,
9875
9876            Component_Definition =>
9877              Make_Component_Definition (Loc,
9878                Aliased_Present     => True,
9879                Subtype_Indication  => Make_Subtype_Indication (Loc,
9880                  Subtype_Mark =>
9881                    New_Occurrence_Of (RTE (RE_Storage_Array), Loc),
9882
9883                  Constraint   =>
9884                    Make_Index_Or_Discriminant_Constraint (Loc,
9885                      Constraints  => New_List (Make_Range (Loc,
9886                        Low_Bound  => Make_Integer_Literal (Loc, 1),
9887                        High_Bound => Convert_To (RTE (RE_Storage_Offset),
9888                          Task_Size)))))));
9889
9890          Append_To (Cdecls, Decl_Stack);
9891
9892          --  The appropriate alignment for the stack is ensured by the run-time
9893          --  code in charge of task creation.
9894
9895       end if;
9896
9897       --  Add components for entry families
9898
9899       Collect_Entry_Families (Loc, Cdecls, Size_Decl, Tasktyp);
9900
9901       --  Add the _Priority component if a Priority pragma is present
9902
9903       if Present (Taskdef) and then Has_Priority_Pragma (Taskdef) then
9904          declare
9905             Prag : constant Node_Id :=
9906                      Find_Task_Or_Protected_Pragma (Taskdef, Name_Priority);
9907             Expr : Node_Id;
9908
9909          begin
9910             Expr := First (Pragma_Argument_Associations (Prag));
9911
9912             if Nkind (Expr) = N_Pragma_Argument_Association then
9913                Expr := Expression (Expr);
9914             end if;
9915
9916             Expr := New_Copy_Tree (Expr);
9917
9918             --  Add conversion to proper type to do range check if required
9919             --  Note that for runtime units, we allow out of range interrupt
9920             --  priority values to be used in a priority pragma. This is for
9921             --  the benefit of some versions of System.Interrupts which use
9922             --  a special server task with maximum interrupt priority.
9923
9924             if Pragma_Name (Prag) = Name_Priority
9925               and then not GNAT_Mode
9926             then
9927                Rewrite (Expr, Convert_To (RTE (RE_Priority), Expr));
9928             else
9929                Rewrite (Expr, Convert_To (RTE (RE_Any_Priority), Expr));
9930             end if;
9931
9932             Append_To (Cdecls,
9933               Make_Component_Declaration (Loc,
9934                 Defining_Identifier =>
9935                   Make_Defining_Identifier (Loc, Name_uPriority),
9936                 Component_Definition =>
9937                   Make_Component_Definition (Loc,
9938                     Aliased_Present    => False,
9939                     Subtype_Indication => New_Reference_To (Standard_Integer,
9940                                                             Loc)),
9941                 Expression => Expr));
9942          end;
9943       end if;
9944
9945       --  Add the _Task_Size component if a Storage_Size pragma is present
9946
9947       if Present (Taskdef)
9948         and then Has_Storage_Size_Pragma (Taskdef)
9949       then
9950          Append_To (Cdecls,
9951            Make_Component_Declaration (Loc,
9952              Defining_Identifier =>
9953                Make_Defining_Identifier (Loc, Name_uSize),
9954
9955              Component_Definition =>
9956                Make_Component_Definition (Loc,
9957                  Aliased_Present    => False,
9958                  Subtype_Indication => New_Reference_To (RTE (RE_Size_Type),
9959                                                          Loc)),
9960
9961              Expression =>
9962                Convert_To (RTE (RE_Size_Type),
9963                  Relocate_Node (
9964                    Expression (First (
9965                      Pragma_Argument_Associations (
9966                        Find_Task_Or_Protected_Pragma
9967                          (Taskdef, Name_Storage_Size))))))));
9968       end if;
9969
9970       --  Add the _Task_Info component if a Task_Info pragma is present
9971
9972       if Present (Taskdef) and then Has_Task_Info_Pragma (Taskdef) then
9973          Append_To (Cdecls,
9974            Make_Component_Declaration (Loc,
9975              Defining_Identifier =>
9976                Make_Defining_Identifier (Loc, Name_uTask_Info),
9977
9978              Component_Definition =>
9979                Make_Component_Definition (Loc,
9980                  Aliased_Present    => False,
9981                  Subtype_Indication =>
9982                    New_Reference_To (RTE (RE_Task_Info_Type), Loc)),
9983
9984              Expression => New_Copy (
9985                Expression (First (
9986                  Pragma_Argument_Associations (
9987                    Find_Task_Or_Protected_Pragma
9988                      (Taskdef, Name_Task_Info)))))));
9989       end if;
9990
9991       --  Add the _Relative_Deadline component if a Relative_Deadline pragma is
9992       --  present. If we are using a restricted run time this component will
9993       --  not be added (deadlines are not allowed by the Ravenscar profile).
9994
9995       if not Restricted_Profile
9996         and then Present (Taskdef)
9997         and then Has_Relative_Deadline_Pragma (Taskdef)
9998       then
9999          Append_To (Cdecls,
10000            Make_Component_Declaration (Loc,
10001              Defining_Identifier =>
10002                Make_Defining_Identifier (Loc, Name_uRelative_Deadline),
10003
10004              Component_Definition =>
10005                Make_Component_Definition (Loc,
10006                  Aliased_Present    => False,
10007                  Subtype_Indication =>
10008                    New_Reference_To (RTE (RE_Time_Span), Loc)),
10009
10010              Expression =>
10011                Convert_To (RTE (RE_Time_Span),
10012                  Relocate_Node (
10013                    Expression (First (
10014                      Pragma_Argument_Associations (
10015                        Find_Task_Or_Protected_Pragma
10016                          (Taskdef, Name_Relative_Deadline))))))));
10017       end if;
10018
10019       Insert_After (Size_Decl, Rec_Decl);
10020
10021       --  Analyze the record declaration immediately after construction,
10022       --  because the initialization procedure is needed for single task
10023       --  declarations before the next entity is analyzed.
10024
10025       Analyze (Rec_Decl);
10026
10027       --  Create the declaration of the task body procedure
10028
10029       Proc_Spec := Build_Task_Proc_Specification (Tasktyp);
10030       Body_Decl :=
10031         Make_Subprogram_Declaration (Loc,
10032           Specification => Proc_Spec);
10033
10034       Insert_After (Rec_Decl, Body_Decl);
10035
10036       --  The subprogram does not comes from source, so we have to indicate the
10037       --  need for debugging information explicitly.
10038
10039       if Comes_From_Source (Original_Node (N)) then
10040          Set_Debug_Info_Needed (Defining_Entity (Proc_Spec));
10041       end if;
10042
10043       --  Ada 2005 (AI-345): Construct the primitive entry wrapper specs before
10044       --  the corresponding record has been frozen.
10045
10046       if Ada_Version >= Ada_05 then
10047          Build_Wrapper_Specs (Loc, Tasktyp, Rec_Decl);
10048       end if;
10049
10050       --  Ada 2005 (AI-345): We must defer freezing to allow further
10051       --  declaration of primitive subprograms covering task interfaces
10052
10053       if Ada_Version <= Ada_95 then
10054
10055          --  Now we can freeze the corresponding record. This needs manually
10056          --  freezing, since it is really part of the task type, and the task
10057          --  type is frozen at this stage. We of course need the initialization
10058          --  procedure for this corresponding record type and we won't get it
10059          --  in time if we don't freeze now.
10060
10061          declare
10062             L : constant List_Id := Freeze_Entity (Rec_Ent, Loc);
10063          begin
10064             if Is_Non_Empty_List (L) then
10065                Insert_List_After (Body_Decl, L);
10066             end if;
10067          end;
10068       end if;
10069
10070       --  Complete the expansion of access types to the current task type, if
10071       --  any were declared.
10072
10073       Expand_Previous_Access_Type (Tasktyp);
10074    end Expand_N_Task_Type_Declaration;
10075
10076    -------------------------------
10077    -- Expand_N_Timed_Entry_Call --
10078    -------------------------------
10079
10080    --  A timed entry call in normal case is not implemented using ATC mechanism
10081    --  anymore for efficiency reason.
10082
10083    --     select
10084    --        T.E;
10085    --        S1;
10086    --     or
10087    --        Delay D;
10088    --        S2;
10089    --     end select;
10090
10091    --  is expanded as follow:
10092
10093    --  1) When T.E is a task entry_call;
10094
10095    --    declare
10096    --       B  : Boolean;
10097    --       X  : Task_Entry_Index := <entry index>;
10098    --       DX : Duration := To_Duration (D);
10099    --       M  : Delay_Mode := <discriminant>;
10100    --       P  : parms := (parm, parm, parm);
10101
10102    --    begin
10103    --       Timed_Protected_Entry_Call
10104    --         (<acceptor-task>, X, P'Address, DX, M, B);
10105    --       if B then
10106    --          S1;
10107    --       else
10108    --          S2;
10109    --       end if;
10110    --    end;
10111
10112    --  2) When T.E is a protected entry_call;
10113
10114    --    declare
10115    --       B  : Boolean;
10116    --       X  : Protected_Entry_Index := <entry index>;
10117    --       DX : Duration := To_Duration (D);
10118    --       M  : Delay_Mode := <discriminant>;
10119    --       P  : parms := (parm, parm, parm);
10120
10121    --    begin
10122    --       Timed_Protected_Entry_Call
10123    --         (<object>'unchecked_access, X, P'Address, DX, M, B);
10124    --       if B then
10125    --          S1;
10126    --       else
10127    --          S2;
10128    --       end if;
10129    --    end;
10130
10131    --  3) Ada 2005 (AI-345): When T.E is a dispatching procedure call;
10132
10133    --    declare
10134    --       B  : Boolean := False;
10135    --       C  : Ada.Tags.Prim_Op_Kind;
10136    --       DX : Duration := To_Duration (D)
10137    --       K  : Ada.Tags.Tagged_Kind :=
10138    --              Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
10139    --       M  : Integer :=...;
10140    --       P  : Parameters := (Param1 .. ParamN);
10141    --       S  : Iteger;
10142
10143    --    begin
10144    --       if K = Ada.Tags.TK_Limited_Tagged then
10145    --          <dispatching-call>;
10146    --          <triggering-statements>
10147
10148    --       else
10149    --          S :=
10150    --            Ada.Tags.Get_Offset_Index
10151    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
10152
10153    --          _Disp_Timed_Select (<object>, S, P'Address, DX, M, C, B);
10154
10155    --          if C = POK_Protected_Entry
10156    --            or else C = POK_Task_Entry
10157    --          then
10158    --             Param1 := P.Param1;
10159    --             ...
10160    --             ParamN := P.ParamN;
10161    --          end if;
10162
10163    --          if B then
10164    --             if C = POK_Procedure
10165    --               or else C = POK_Protected_Procedure
10166    --               or else C = POK_Task_Procedure
10167    --             then
10168    --                <dispatching-call>;
10169    --             end if;
10170
10171    --             <triggering-statements>
10172    --          else
10173    --             <timed-statements>
10174    --          end if;
10175    --       end if;
10176    --    end;
10177
10178    procedure Expand_N_Timed_Entry_Call (N : Node_Id) is
10179       Loc : constant Source_Ptr := Sloc (N);
10180
10181       E_Call  : Node_Id :=
10182                   Entry_Call_Statement (Entry_Call_Alternative (N));
10183       E_Stats : constant List_Id :=
10184                   Statements (Entry_Call_Alternative (N));
10185       D_Stat  : Node_Id :=
10186                   Delay_Statement (Delay_Alternative (N));
10187       D_Stats : constant List_Id :=
10188                   Statements (Delay_Alternative (N));
10189
10190       Actuals        : List_Id;
10191       Blk_Typ        : Entity_Id;
10192       Call           : Node_Id;
10193       Call_Ent       : Entity_Id;
10194       Conc_Typ_Stmts : List_Id;
10195       Concval        : Node_Id;
10196       D_Conv         : Node_Id;
10197       D_Disc         : Node_Id;
10198       D_Type         : Entity_Id;
10199       Decls          : List_Id;
10200       Dummy          : Node_Id;
10201       Ename          : Node_Id;
10202       Formals        : List_Id;
10203       Index          : Node_Id;
10204       Is_Disp_Select : Boolean;
10205       Lim_Typ_Stmts  : List_Id;
10206       N_Stats        : List_Id;
10207       Obj            : Entity_Id;
10208       Param          : Node_Id;
10209       Params         : List_Id;
10210       Stmt           : Node_Id;
10211       Stmts          : List_Id;
10212       Unpack         : List_Id;
10213
10214       B : Entity_Id;  --  Call status flag
10215       C : Entity_Id;  --  Call kind
10216       D : Entity_Id;  --  Delay
10217       K : Entity_Id;  --  Tagged kind
10218       M : Entity_Id;  --  Delay mode
10219       P : Entity_Id;  --  Parameter block
10220       S : Entity_Id;  --  Primitive operation slot
10221
10222    begin
10223       --  The arguments in the call may require dynamic allocation, and the
10224       --  call statement may have been transformed into a block. The block
10225       --  may contain additional declarations for internal entities, and the
10226       --  original call is found by sequential search.
10227
10228       if Nkind (E_Call) = N_Block_Statement then
10229          E_Call := First (Statements (Handled_Statement_Sequence (E_Call)));
10230          while not Nkind_In (E_Call, N_Procedure_Call_Statement,
10231                                      N_Entry_Call_Statement)
10232          loop
10233             Next (E_Call);
10234          end loop;
10235       end if;
10236
10237       Is_Disp_Select :=
10238         Ada_Version >= Ada_05
10239           and then Nkind (E_Call) = N_Procedure_Call_Statement;
10240
10241       if Is_Disp_Select then
10242          Extract_Dispatching_Call (E_Call, Call_Ent, Obj, Actuals, Formals);
10243
10244          Decls := New_List;
10245          Stmts := New_List;
10246
10247          --  Generate:
10248          --    B : Boolean := False;
10249
10250          B := Build_B (Loc, Decls);
10251
10252          --  Generate:
10253          --    C : Ada.Tags.Prim_Op_Kind;
10254
10255          C := Build_C (Loc, Decls);
10256
10257          --  Because the analysis of all statements was disabled, manually
10258          --  analyze the delay statement.
10259
10260          Analyze (D_Stat);
10261          D_Stat := Original_Node (D_Stat);
10262
10263       else
10264          --  Build an entry call using Simple_Entry_Call
10265
10266          Extract_Entry (E_Call, Concval, Ename, Index);
10267          Build_Simple_Entry_Call (E_Call, Concval, Ename, Index);
10268
10269          Decls := Declarations (E_Call);
10270          Stmts := Statements (Handled_Statement_Sequence (E_Call));
10271
10272          if No (Decls) then
10273             Decls := New_List;
10274          end if;
10275
10276          --  Generate:
10277          --    B : Boolean;
10278
10279          B := Make_Defining_Identifier (Loc, Name_uB);
10280
10281          Prepend_To (Decls,
10282            Make_Object_Declaration (Loc,
10283              Defining_Identifier =>
10284                B,
10285              Object_Definition =>
10286                New_Reference_To (Standard_Boolean, Loc)));
10287       end if;
10288
10289       --  Duration and mode processing
10290
10291       D_Type := Base_Type (Etype (Expression (D_Stat)));
10292
10293       --  Use the type of the delay expression (Calendar or Real_Time) to
10294       --  generate the appropriate conversion.
10295
10296       if Nkind (D_Stat) = N_Delay_Relative_Statement then
10297          D_Disc := Make_Integer_Literal (Loc, 0);
10298          D_Conv := Relocate_Node (Expression (D_Stat));
10299
10300       elsif Is_RTE (D_Type, RO_CA_Time) then
10301          D_Disc := Make_Integer_Literal (Loc, 1);
10302          D_Conv := Make_Function_Call (Loc,
10303            New_Reference_To (RTE (RO_CA_To_Duration), Loc),
10304            New_List (New_Copy (Expression (D_Stat))));
10305
10306       else pragma Assert (Is_RTE (D_Type, RO_RT_Time));
10307          D_Disc := Make_Integer_Literal (Loc, 2);
10308          D_Conv := Make_Function_Call (Loc,
10309            New_Reference_To (RTE (RO_RT_To_Duration), Loc),
10310            New_List (New_Copy (Expression (D_Stat))));
10311       end if;
10312
10313       D := Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
10314
10315       --  Generate:
10316       --    D : Duration;
10317
10318       Append_To (Decls,
10319         Make_Object_Declaration (Loc,
10320           Defining_Identifier =>
10321             D,
10322           Object_Definition =>
10323             New_Reference_To (Standard_Duration, Loc)));
10324
10325       M := Make_Defining_Identifier (Loc, New_Internal_Name ('M'));
10326
10327       --  Generate:
10328       --    M : Integer := (0 | 1 | 2);
10329
10330       Append_To (Decls,
10331         Make_Object_Declaration (Loc,
10332           Defining_Identifier =>
10333             M,
10334           Object_Definition =>
10335             New_Reference_To (Standard_Integer, Loc),
10336           Expression =>
10337             D_Disc));
10338
10339       --  Do the assignment at this stage only because the evaluation of the
10340       --  expression must not occur before (see ACVC C97302A).
10341
10342       Append_To (Stmts,
10343         Make_Assignment_Statement (Loc,
10344           Name =>
10345             New_Reference_To (D, Loc),
10346           Expression =>
10347             D_Conv));
10348
10349       --  Parameter block processing
10350
10351       --  Manually create the parameter block for dispatching calls. In the
10352       --  case of entries, the block has already been created during the call
10353       --  to Build_Simple_Entry_Call.
10354
10355       if Is_Disp_Select then
10356
10357          --  Tagged kind processing, generate:
10358          --    K : Ada.Tags.Tagged_Kind :=
10359          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag <object>));
10360
10361          K := Build_K (Loc, Decls, Obj);
10362
10363          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
10364          P := Parameter_Block_Pack
10365                 (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
10366
10367          --  Dispatch table slot processing, generate:
10368          --    S : Integer;
10369
10370          S := Build_S (Loc, Decls);
10371
10372          --  Generate:
10373          --    S := Ada.Tags.Get_Offset_Index
10374          --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
10375
10376          Conc_Typ_Stmts :=
10377            New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
10378
10379          --  Generate:
10380          --    _Disp_Timed_Select (<object>, S, P'Address, D, M, C, B);
10381
10382          --  where Obj is the controlling formal parameter, S is the dispatch
10383          --  table slot number of the dispatching operation, P is the wrapped
10384          --  parameter block, D is the duration, M is the duration mode, C is
10385          --  the call kind and B is the call status.
10386
10387          Params := New_List;
10388
10389          Append_To (Params, New_Copy_Tree (Obj));
10390          Append_To (Params, New_Reference_To (S, Loc));
10391          Append_To (Params, Make_Attribute_Reference (Loc,
10392                               Prefix => New_Reference_To (P, Loc),
10393                               Attribute_Name => Name_Address));
10394          Append_To (Params, New_Reference_To (D, Loc));
10395          Append_To (Params, New_Reference_To (M, Loc));
10396          Append_To (Params, New_Reference_To (C, Loc));
10397          Append_To (Params, New_Reference_To (B, Loc));
10398
10399          Append_To (Conc_Typ_Stmts,
10400            Make_Procedure_Call_Statement (Loc,
10401              Name =>
10402                New_Reference_To (
10403                  Find_Prim_Op (Etype (Etype (Obj)),
10404                    Name_uDisp_Timed_Select),
10405                  Loc),
10406              Parameter_Associations =>
10407                Params));
10408
10409          --  Generate:
10410          --    if C = POK_Protected_Entry
10411          --      or else C = POK_Task_Entry
10412          --    then
10413          --       Param1 := P.Param1;
10414          --       ...
10415          --       ParamN := P.ParamN;
10416          --    end if;
10417
10418          Unpack := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
10419
10420          --  Generate the if statement only when the packed parameters need
10421          --  explicit assignments to their corresponding actuals.
10422
10423          if Present (Unpack) then
10424             Append_To (Conc_Typ_Stmts,
10425               Make_If_Statement (Loc,
10426
10427                 Condition =>
10428                   Make_Or_Else (Loc,
10429                     Left_Opnd =>
10430                       Make_Op_Eq (Loc,
10431                         Left_Opnd =>
10432                           New_Reference_To (C, Loc),
10433                         Right_Opnd =>
10434                           New_Reference_To (RTE (
10435                             RE_POK_Protected_Entry), Loc)),
10436                     Right_Opnd =>
10437                       Make_Op_Eq (Loc,
10438                         Left_Opnd =>
10439                           New_Reference_To (C, Loc),
10440                         Right_Opnd =>
10441                           New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
10442
10443                 Then_Statements =>
10444                   Unpack));
10445          end if;
10446
10447          --  Generate:
10448
10449          --    if B then
10450          --       if C = POK_Procedure
10451          --         or else C = POK_Protected_Procedure
10452          --         or else C = POK_Task_Procedure
10453          --       then
10454          --          <dispatching-call>
10455          --       end if;
10456          --       <triggering-statements>
10457          --    else
10458          --       <timed-statements>
10459          --    end if;
10460
10461          N_Stats := New_Copy_List_Tree (E_Stats);
10462
10463          Prepend_To (N_Stats,
10464            Make_If_Statement (Loc,
10465
10466              Condition =>
10467                Make_Or_Else (Loc,
10468                  Left_Opnd =>
10469                    Make_Op_Eq (Loc,
10470                      Left_Opnd =>
10471                        New_Reference_To (C, Loc),
10472                      Right_Opnd =>
10473                        New_Reference_To (RTE (RE_POK_Procedure), Loc)),
10474                  Right_Opnd =>
10475                    Make_Or_Else (Loc,
10476                      Left_Opnd =>
10477                        Make_Op_Eq (Loc,
10478                          Left_Opnd =>
10479                            New_Reference_To (C, Loc),
10480                          Right_Opnd =>
10481                            New_Reference_To (RTE (
10482                              RE_POK_Protected_Procedure), Loc)),
10483                      Right_Opnd =>
10484                        Make_Op_Eq (Loc,
10485                          Left_Opnd =>
10486                            New_Reference_To (C, Loc),
10487                          Right_Opnd =>
10488                            New_Reference_To (RTE (
10489                              RE_POK_Task_Procedure), Loc)))),
10490
10491              Then_Statements =>
10492                New_List (E_Call)));
10493
10494          Append_To (Conc_Typ_Stmts,
10495            Make_If_Statement (Loc,
10496              Condition => New_Reference_To (B, Loc),
10497              Then_Statements => N_Stats,
10498              Else_Statements => D_Stats));
10499
10500          --  Generate:
10501          --    <dispatching-call>;
10502          --    <triggering-statements>
10503
10504          Lim_Typ_Stmts := New_Copy_List_Tree (E_Stats);
10505          Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (E_Call));
10506
10507          --  Generate:
10508          --    if K = Ada.Tags.TK_Limited_Tagged then
10509          --       Lim_Typ_Stmts
10510          --    else
10511          --       Conc_Typ_Stmts
10512          --    end if;
10513
10514          Append_To (Stmts,
10515            Make_If_Statement (Loc,
10516              Condition =>
10517                Make_Op_Eq (Loc,
10518                  Left_Opnd =>
10519                    New_Reference_To (K, Loc),
10520                  Right_Opnd =>
10521                    New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
10522
10523              Then_Statements =>
10524                Lim_Typ_Stmts,
10525
10526              Else_Statements =>
10527                Conc_Typ_Stmts));
10528
10529       else
10530          --  Skip assignments to temporaries created for in-out parameters.
10531          --  This makes unwarranted assumptions about the shape of the expanded
10532          --  tree for the call, and should be cleaned up ???
10533
10534          Stmt := First (Stmts);
10535          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
10536             Next (Stmt);
10537          end loop;
10538
10539          --  Do the assignment at this stage only because the evaluation
10540          --  of the expression must not occur before (see ACVC C97302A).
10541
10542          Insert_Before (Stmt,
10543            Make_Assignment_Statement (Loc,
10544              Name => New_Reference_To (D, Loc),
10545              Expression => D_Conv));
10546
10547          Call   := Stmt;
10548          Params := Parameter_Associations (Call);
10549
10550          --  For a protected type, we build a Timed_Protected_Entry_Call
10551
10552          if Is_Protected_Type (Etype (Concval)) then
10553
10554             --  Create a new call statement
10555
10556             Param := First (Params);
10557             while Present (Param)
10558               and then not Is_RTE (Etype (Param), RE_Call_Modes)
10559             loop
10560                Next (Param);
10561             end loop;
10562
10563             Dummy := Remove_Next (Next (Param));
10564
10565             --  Remove garbage is following the Cancel_Param if present
10566
10567             Dummy := Next (Param);
10568
10569             --  Remove the mode of the Protected_Entry_Call call, then remove
10570             --  the Communication_Block of the Protected_Entry_Call call, and
10571             --  finally add Duration and a Delay_Mode parameter
10572
10573             pragma Assert (Present (Param));
10574             Rewrite (Param, New_Reference_To (D, Loc));
10575
10576             Rewrite (Dummy, New_Reference_To (M, Loc));
10577
10578             --  Add a Boolean flag for successful entry call
10579
10580             Append_To (Params, New_Reference_To (B, Loc));
10581
10582             case Corresponding_Runtime_Package (Etype (Concval)) is
10583                when System_Tasking_Protected_Objects_Entries =>
10584                   Rewrite (Call,
10585                     Make_Procedure_Call_Statement (Loc,
10586                       Name =>
10587                         New_Reference_To
10588                           (RTE (RE_Timed_Protected_Entry_Call), Loc),
10589                       Parameter_Associations => Params));
10590
10591                when System_Tasking_Protected_Objects_Single_Entry =>
10592                   Param := First (Params);
10593                   while Present (Param)
10594                     and then not
10595                       Is_RTE (Etype (Param), RE_Protected_Entry_Index)
10596                   loop
10597                      Next (Param);
10598                   end loop;
10599
10600                   Remove (Param);
10601
10602                   Rewrite (Call,
10603                     Make_Procedure_Call_Statement (Loc,
10604                       Name => New_Reference_To (
10605                         RTE (RE_Timed_Protected_Single_Entry_Call), Loc),
10606                       Parameter_Associations => Params));
10607
10608                when others =>
10609                   raise Program_Error;
10610             end case;
10611
10612          --  For the task case, build a Timed_Task_Entry_Call
10613
10614          else
10615             --  Create a new call statement
10616
10617             Append_To (Params, New_Reference_To (D, Loc));
10618             Append_To (Params, New_Reference_To (M, Loc));
10619             Append_To (Params, New_Reference_To (B, Loc));
10620
10621             Rewrite (Call,
10622               Make_Procedure_Call_Statement (Loc,
10623                 Name =>
10624                   New_Reference_To (RTE (RE_Timed_Task_Entry_Call), Loc),
10625                 Parameter_Associations => Params));
10626          end if;
10627
10628          Append_To (Stmts,
10629            Make_Implicit_If_Statement (N,
10630              Condition => New_Reference_To (B, Loc),
10631              Then_Statements => E_Stats,
10632              Else_Statements => D_Stats));
10633       end if;
10634
10635       Rewrite (N,
10636         Make_Block_Statement (Loc,
10637           Declarations => Decls,
10638           Handled_Statement_Sequence =>
10639             Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
10640
10641       Analyze (N);
10642    end Expand_N_Timed_Entry_Call;
10643
10644    ----------------------------------------
10645    -- Expand_Protected_Body_Declarations --
10646    ----------------------------------------
10647
10648    procedure Expand_Protected_Body_Declarations
10649      (N       : Node_Id;
10650       Spec_Id : Entity_Id)
10651    is
10652    begin
10653       if No_Run_Time_Mode then
10654          Error_Msg_CRT ("protected body", N);
10655          return;
10656
10657       elsif Expander_Active then
10658
10659          --  Associate discriminals with the first subprogram or entry body to
10660          --  be expanded.
10661
10662          if Present (First_Protected_Operation (Declarations (N))) then
10663             Set_Discriminals (Parent (Spec_Id));
10664          end if;
10665       end if;
10666    end Expand_Protected_Body_Declarations;
10667
10668    -------------------------
10669    -- External_Subprogram --
10670    -------------------------
10671
10672    function External_Subprogram (E : Entity_Id) return Entity_Id is
10673       Subp : constant Entity_Id := Protected_Body_Subprogram (E);
10674
10675    begin
10676       --  The internal and external subprograms follow each other on the entity
10677       --  chain. Note that previously private operations had no separate
10678       --  external subprogram. We now create one in all cases, because a
10679       --  private operation may actually appear in an external call, through
10680       --  a 'Access reference used for a callback.
10681
10682       --  If the operation is a function that returns an anonymous access type,
10683       --  the corresponding itype appears before the operation, and must be
10684       --  skipped.
10685
10686       --  This mechanism is fragile, there should be a real link between the
10687       --  two versions of the operation, but there is no place to put it ???
10688
10689       if Is_Access_Type (Next_Entity (Subp)) then
10690          return Next_Entity (Next_Entity (Subp));
10691       else
10692          return Next_Entity (Subp);
10693       end if;
10694    end External_Subprogram;
10695
10696    ------------------------------
10697    -- Extract_Dispatching_Call --
10698    ------------------------------
10699
10700    procedure Extract_Dispatching_Call
10701      (N        : Node_Id;
10702       Call_Ent : out Entity_Id;
10703       Object   : out Entity_Id;
10704       Actuals  : out List_Id;
10705       Formals  : out List_Id)
10706    is
10707       Call_Nam : Node_Id;
10708
10709    begin
10710       pragma Assert (Nkind (N) = N_Procedure_Call_Statement);
10711
10712       if Present (Original_Node (N)) then
10713          Call_Nam := Name (Original_Node (N));
10714       else
10715          Call_Nam := Name (N);
10716       end if;
10717
10718       --  Retrieve the name of the dispatching procedure. It contains the
10719       --  dispatch table slot number.
10720
10721       loop
10722          case Nkind (Call_Nam) is
10723             when N_Identifier =>
10724                exit;
10725
10726             when N_Selected_Component =>
10727                Call_Nam := Selector_Name (Call_Nam);
10728
10729             when others =>
10730                raise Program_Error;
10731
10732          end case;
10733       end loop;
10734
10735       Actuals  := Parameter_Associations (N);
10736       Call_Ent := Entity (Call_Nam);
10737       Formals  := Parameter_Specifications (Parent (Call_Ent));
10738       Object   := First (Actuals);
10739
10740       if Present (Original_Node (Object)) then
10741          Object := Original_Node (Object);
10742       end if;
10743    end Extract_Dispatching_Call;
10744
10745    -------------------
10746    -- Extract_Entry --
10747    -------------------
10748
10749    procedure Extract_Entry
10750      (N       : Node_Id;
10751       Concval : out Node_Id;
10752       Ename   : out Node_Id;
10753       Index   : out Node_Id)
10754    is
10755       Nam : constant Node_Id := Name (N);
10756
10757    begin
10758       --  For a simple entry, the name is a selected component, with the
10759       --  prefix being the task value, and the selector being the entry.
10760
10761       if Nkind (Nam) = N_Selected_Component then
10762          Concval := Prefix (Nam);
10763          Ename   := Selector_Name (Nam);
10764          Index   := Empty;
10765
10766       --  For a member of an entry family, the name is an indexed component
10767       --  where the prefix is a selected component, whose prefix in turn is
10768       --  the task value, and whose selector is the entry family. The single
10769       --  expression in the expressions list of the indexed component is the
10770       --  subscript for the family.
10771
10772       else pragma Assert (Nkind (Nam) = N_Indexed_Component);
10773          Concval := Prefix (Prefix (Nam));
10774          Ename   := Selector_Name (Prefix (Nam));
10775          Index   := First (Expressions (Nam));
10776       end if;
10777    end Extract_Entry;
10778
10779    -------------------
10780    -- Family_Offset --
10781    -------------------
10782
10783    function Family_Offset
10784      (Loc  : Source_Ptr;
10785       Hi   : Node_Id;
10786       Lo   : Node_Id;
10787       Ttyp : Entity_Id;
10788       Cap  : Boolean) return Node_Id
10789    is
10790       Ityp : Entity_Id;
10791       Real_Hi : Node_Id;
10792       Real_Lo : Node_Id;
10793
10794       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id;
10795       --  If one of the bounds is a reference to a discriminant, replace with
10796       --  corresponding discriminal of type. Within the body of a task retrieve
10797       --  the renamed discriminant by simple visibility, using its generated
10798       --  name. Within a protected object, find the original discriminant and
10799       --  replace it with the discriminal of the current protected operation.
10800
10801       ------------------------------
10802       -- Convert_Discriminant_Ref --
10803       ------------------------------
10804
10805       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id is
10806          Loc : constant Source_Ptr := Sloc (Bound);
10807          B   : Node_Id;
10808          D   : Entity_Id;
10809
10810       begin
10811          if Is_Entity_Name (Bound)
10812            and then Ekind (Entity (Bound)) = E_Discriminant
10813          then
10814             if Is_Task_Type (Ttyp)
10815               and then Has_Completion (Ttyp)
10816             then
10817                B := Make_Identifier (Loc, Chars (Entity (Bound)));
10818                Find_Direct_Name (B);
10819
10820             elsif Is_Protected_Type (Ttyp) then
10821                D := First_Discriminant (Ttyp);
10822                while Chars (D) /= Chars (Entity (Bound)) loop
10823                   Next_Discriminant (D);
10824                end loop;
10825
10826                B := New_Reference_To  (Discriminal (D), Loc);
10827
10828             else
10829                B := New_Reference_To (Discriminal (Entity (Bound)), Loc);
10830             end if;
10831
10832          elsif Nkind (Bound) = N_Attribute_Reference then
10833             return Bound;
10834
10835          else
10836             B := New_Copy_Tree (Bound);
10837          end if;
10838
10839          return
10840            Make_Attribute_Reference (Loc,
10841              Attribute_Name => Name_Pos,
10842              Prefix => New_Occurrence_Of (Etype (Bound), Loc),
10843              Expressions    => New_List (B));
10844       end Convert_Discriminant_Ref;
10845
10846    --  Start of processing for Family_Offset
10847
10848    begin
10849       Real_Hi := Convert_Discriminant_Ref (Hi);
10850       Real_Lo := Convert_Discriminant_Ref (Lo);
10851
10852       if Cap then
10853          if Is_Task_Type (Ttyp) then
10854             Ityp := RTE (RE_Task_Entry_Index);
10855          else
10856             Ityp := RTE (RE_Protected_Entry_Index);
10857          end if;
10858
10859          Real_Hi :=
10860            Make_Attribute_Reference (Loc,
10861              Prefix         => New_Reference_To (Ityp, Loc),
10862              Attribute_Name => Name_Min,
10863              Expressions    => New_List (
10864                Real_Hi,
10865                Make_Integer_Literal (Loc, Entry_Family_Bound - 1)));
10866
10867          Real_Lo :=
10868            Make_Attribute_Reference (Loc,
10869              Prefix         => New_Reference_To (Ityp, Loc),
10870              Attribute_Name => Name_Max,
10871              Expressions    => New_List (
10872                Real_Lo,
10873                Make_Integer_Literal (Loc, -Entry_Family_Bound)));
10874       end if;
10875
10876       return Make_Op_Subtract (Loc, Real_Hi, Real_Lo);
10877    end Family_Offset;
10878
10879    -----------------
10880    -- Family_Size --
10881    -----------------
10882
10883    function Family_Size
10884      (Loc  : Source_Ptr;
10885       Hi   : Node_Id;
10886       Lo   : Node_Id;
10887       Ttyp : Entity_Id;
10888       Cap  : Boolean) return Node_Id
10889    is
10890       Ityp : Entity_Id;
10891
10892    begin
10893       if Is_Task_Type (Ttyp) then
10894          Ityp := RTE (RE_Task_Entry_Index);
10895       else
10896          Ityp := RTE (RE_Protected_Entry_Index);
10897       end if;
10898
10899       return
10900         Make_Attribute_Reference (Loc,
10901           Prefix         => New_Reference_To (Ityp, Loc),
10902           Attribute_Name => Name_Max,
10903           Expressions    => New_List (
10904             Make_Op_Add (Loc,
10905               Left_Opnd  =>
10906                 Family_Offset (Loc, Hi, Lo, Ttyp, Cap),
10907               Right_Opnd =>
10908                 Make_Integer_Literal (Loc, 1)),
10909             Make_Integer_Literal (Loc, 0)));
10910    end Family_Size;
10911
10912    -----------------------------------
10913    -- Find_Task_Or_Protected_Pragma --
10914    -----------------------------------
10915
10916    function Find_Task_Or_Protected_Pragma
10917      (T : Node_Id;
10918       P : Name_Id) return Node_Id
10919    is
10920       N : Node_Id;
10921
10922    begin
10923       N := First (Visible_Declarations (T));
10924       while Present (N) loop
10925          if Nkind (N) = N_Pragma then
10926             if Pragma_Name (N) = P then
10927                return N;
10928
10929             elsif P = Name_Priority
10930               and then Pragma_Name (N) = Name_Interrupt_Priority
10931             then
10932                return N;
10933
10934             else
10935                Next (N);
10936             end if;
10937
10938          else
10939             Next (N);
10940          end if;
10941       end loop;
10942
10943       N := First (Private_Declarations (T));
10944       while Present (N) loop
10945          if Nkind (N) = N_Pragma then
10946             if Pragma_Name (N) = P then
10947                return N;
10948
10949             elsif P = Name_Priority
10950               and then Pragma_Name (N) = Name_Interrupt_Priority
10951             then
10952                return N;
10953
10954             else
10955                Next (N);
10956             end if;
10957
10958          else
10959             Next (N);
10960          end if;
10961       end loop;
10962
10963       raise Program_Error;
10964    end Find_Task_Or_Protected_Pragma;
10965
10966    -------------------------------
10967    -- First_Protected_Operation --
10968    -------------------------------
10969
10970    function First_Protected_Operation (D : List_Id) return Node_Id is
10971       First_Op : Node_Id;
10972
10973    begin
10974       First_Op := First (D);
10975       while Present (First_Op)
10976         and then not Nkind_In (First_Op, N_Subprogram_Body, N_Entry_Body)
10977       loop
10978          Next (First_Op);
10979       end loop;
10980
10981       return First_Op;
10982    end First_Protected_Operation;
10983
10984    ---------------------------------------
10985    -- Install_Private_Data_Declarations --
10986    ---------------------------------------
10987
10988    procedure Install_Private_Data_Declarations
10989      (Loc      : Source_Ptr;
10990       Spec_Id  : Entity_Id;
10991       Conc_Typ : Entity_Id;
10992       Body_Nod : Node_Id;
10993       Decls    : List_Id;
10994       Barrier  : Boolean := False;
10995       Family   : Boolean := False)
10996    is
10997       Is_Protected : constant Boolean := Is_Protected_Type (Conc_Typ);
10998       Decl         : Node_Id;
10999       Def          : Node_Id;
11000       Insert_Node  : Node_Id := Empty;
11001       Obj_Ent      : Entity_Id;
11002
11003       procedure Add (Decl : Node_Id);
11004       --  Add a single declaration after Insert_Node. If this is the first
11005       --  addition, Decl is added to the front of Decls and it becomes the
11006       --  insertion node.
11007
11008       function Replace_Bound (Bound : Node_Id) return Node_Id;
11009       --  The bounds of an entry index may depend on discriminants, create a
11010       --  reference to the corresponding prival. Otherwise return a duplicate
11011       --  of the original bound.
11012
11013       ---------
11014       -- Add --
11015       ---------
11016
11017       procedure Add (Decl : Node_Id) is
11018       begin
11019          if No (Insert_Node) then
11020             Prepend_To (Decls, Decl);
11021          else
11022             Insert_After (Insert_Node, Decl);
11023          end if;
11024
11025          Insert_Node := Decl;
11026       end Add;
11027
11028       --------------------------
11029       -- Replace_Discriminant --
11030       --------------------------
11031
11032       function Replace_Bound (Bound : Node_Id) return Node_Id is
11033       begin
11034          if Nkind (Bound) = N_Identifier
11035            and then Is_Discriminal (Entity (Bound))
11036          then
11037             return Make_Identifier (Loc, Chars (Entity (Bound)));
11038          else
11039             return Duplicate_Subexpr (Bound);
11040          end if;
11041       end Replace_Bound;
11042
11043    --  Start of processing for Install_Private_Data_Declarations
11044
11045    begin
11046       --  Step 1: Retrieve the concurrent object entity. Obj_Ent can denote
11047       --  formal parameter _O, _object or _task depending on the context.
11048
11049       Obj_Ent := Concurrent_Object (Spec_Id, Conc_Typ);
11050
11051       --  Special processing of _O for barrier functions, protected entries
11052       --  and families.
11053
11054       if Barrier
11055         or else
11056           (Is_Protected
11057              and then
11058                (Ekind (Spec_Id) = E_Entry
11059                   or else Ekind (Spec_Id) = E_Entry_Family))
11060       then
11061          declare
11062             Conc_Rec : constant Entity_Id :=
11063                          Corresponding_Record_Type (Conc_Typ);
11064             Typ_Id   : constant Entity_Id :=
11065                          Make_Defining_Identifier (Loc,
11066                            New_External_Name (Chars (Conc_Rec), 'P'));
11067          begin
11068             --  Generate:
11069             --    type prot_typVP is access prot_typV;
11070
11071             Decl :=
11072               Make_Full_Type_Declaration (Loc,
11073                 Defining_Identifier => Typ_Id,
11074                 Type_Definition     =>
11075                   Make_Access_To_Object_Definition (Loc,
11076                     Subtype_Indication =>
11077                       New_Reference_To (Conc_Rec, Loc)));
11078             Add (Decl);
11079
11080             --  Generate:
11081             --    _object : prot_typVP := prot_typV (_O);
11082
11083             Decl :=
11084               Make_Object_Declaration (Loc,
11085                 Defining_Identifier =>
11086                   Make_Defining_Identifier (Loc, Name_uObject),
11087                 Object_Definition   => New_Reference_To (Typ_Id, Loc),
11088                 Expression          =>
11089                   Unchecked_Convert_To (Typ_Id,
11090                     New_Reference_To (Obj_Ent, Loc)));
11091             Add (Decl);
11092
11093             --  Set the reference to the concurrent object
11094
11095             Obj_Ent := Defining_Identifier (Decl);
11096          end;
11097       end if;
11098
11099       --  Step 2: Create the Protection object and build its declaration for
11100       --  any protected entry (family) of subprogram.
11101
11102       if Is_Protected then
11103          declare
11104             Prot_Ent : constant Entity_Id :=
11105                          Make_Defining_Identifier (Loc,
11106                            New_Internal_Name ('R'));
11107             Prot_Typ : RE_Id;
11108
11109          begin
11110             Set_Protection_Object (Spec_Id, Prot_Ent);
11111
11112             --  Determine the proper protection type
11113
11114             if Has_Attach_Handler (Conc_Typ)
11115               and then not Restricted_Profile
11116             then
11117                Prot_Typ := RE_Static_Interrupt_Protection;
11118
11119             elsif Has_Interrupt_Handler (Conc_Typ) then
11120                Prot_Typ := RE_Dynamic_Interrupt_Protection;
11121
11122             --  The type has explicit entries or generated primitive entry
11123             --  wrappers.
11124
11125             elsif Has_Entries (Conc_Typ)
11126               or else
11127                 (Ada_Version >= Ada_05
11128                    and then Present (Interface_List (Parent (Conc_Typ))))
11129             then
11130                case Corresponding_Runtime_Package (Conc_Typ) is
11131                   when System_Tasking_Protected_Objects_Entries =>
11132                      Prot_Typ := RE_Protection_Entries;
11133
11134                   when System_Tasking_Protected_Objects_Single_Entry =>
11135                      Prot_Typ := RE_Protection_Entry;
11136
11137                   when others =>
11138                      raise Program_Error;
11139                end case;
11140
11141             else
11142                Prot_Typ := RE_Protection;
11143             end if;
11144
11145             --  Generate:
11146             --    conc_typR : protection_typ renames _object._object;
11147
11148             Decl :=
11149               Make_Object_Renaming_Declaration (Loc,
11150                 Defining_Identifier => Prot_Ent,
11151                 Subtype_Mark =>
11152                   New_Reference_To (RTE (Prot_Typ), Loc),
11153                 Name =>
11154                   Make_Selected_Component (Loc,
11155                     Prefix =>
11156                       New_Reference_To (Obj_Ent, Loc),
11157                     Selector_Name =>
11158                       Make_Identifier (Loc, Name_uObject)));
11159             Add (Decl);
11160          end;
11161       end if;
11162
11163       --  Step 3: Add discriminant renamings (if any)
11164
11165       if Has_Discriminants (Conc_Typ) then
11166          declare
11167             D : Entity_Id;
11168
11169          begin
11170             D := First_Discriminant (Conc_Typ);
11171             while Present (D) loop
11172
11173                --  Adjust the source location
11174
11175                Set_Sloc (Discriminal (D), Loc);
11176
11177                --  Generate:
11178                --    discr_name : discr_typ renames _object.discr_name;
11179                --      or
11180                --    discr_name : discr_typ renames _task.discr_name;
11181
11182                Decl :=
11183                  Make_Object_Renaming_Declaration (Loc,
11184                    Defining_Identifier => Discriminal (D),
11185                    Subtype_Mark        => New_Reference_To (Etype (D), Loc),
11186                    Name                =>
11187                      Make_Selected_Component (Loc,
11188                        Prefix        => New_Reference_To (Obj_Ent, Loc),
11189                        Selector_Name => Make_Identifier (Loc, Chars (D))));
11190                Add (Decl);
11191
11192                Next_Discriminant (D);
11193             end loop;
11194          end;
11195       end if;
11196
11197       --  Step 4: Add private component renamings (if any)
11198
11199       if Is_Protected then
11200          Def := Protected_Definition (Parent (Conc_Typ));
11201
11202          if Present (Private_Declarations (Def)) then
11203             declare
11204                Comp    : Node_Id;
11205                Comp_Id : Entity_Id;
11206                Decl_Id : Entity_Id;
11207
11208             begin
11209                Comp := First (Private_Declarations (Def));
11210                while Present (Comp) loop
11211                   if Nkind (Comp) = N_Component_Declaration then
11212                      Comp_Id := Defining_Identifier (Comp);
11213                      Decl_Id :=
11214                        Make_Defining_Identifier (Loc, Chars (Comp_Id));
11215
11216                      --  Minimal decoration
11217
11218                      if Ekind (Spec_Id) = E_Function then
11219                         Set_Ekind (Decl_Id, E_Constant);
11220                      else
11221                         Set_Ekind (Decl_Id, E_Variable);
11222                      end if;
11223
11224                      Set_Prival      (Comp_Id, Decl_Id);
11225                      Set_Prival_Link (Decl_Id, Comp_Id);
11226                      Set_Is_Aliased  (Decl_Id, Is_Aliased (Comp_Id));
11227
11228                      --  Generate:
11229                      --    comp_name : comp_typ renames _object.comp_name;
11230
11231                      Decl :=
11232                        Make_Object_Renaming_Declaration (Loc,
11233                          Defining_Identifier => Decl_Id,
11234                          Subtype_Mark =>
11235                            New_Reference_To (Etype (Comp_Id), Loc),
11236                          Name =>
11237                            Make_Selected_Component (Loc,
11238                              Prefix =>
11239                                New_Reference_To (Obj_Ent, Loc),
11240                              Selector_Name =>
11241                                Make_Identifier (Loc, Chars (Comp_Id))));
11242                      Add (Decl);
11243                   end if;
11244
11245                   Next (Comp);
11246                end loop;
11247             end;
11248          end if;
11249       end if;
11250
11251       --  Step 5: Add the declaration of the entry index and the associated
11252       --  type for barrier functions and entry families.
11253
11254       if (Barrier and then Family)
11255         or else Ekind (Spec_Id) = E_Entry_Family
11256       then
11257          declare
11258             E         : constant Entity_Id := Index_Object (Spec_Id);
11259             Index     : constant Entity_Id :=
11260                           Defining_Identifier (
11261                             Entry_Index_Specification (
11262                               Entry_Body_Formal_Part (Body_Nod)));
11263             Index_Con : constant Entity_Id :=
11264                           Make_Defining_Identifier (Loc, Chars (Index));
11265             High      : Node_Id;
11266             Index_Typ : Entity_Id;
11267             Low       : Node_Id;
11268
11269          begin
11270             --  Minimal decoration
11271
11272             Set_Ekind                (Index_Con, E_Constant);
11273             Set_Entry_Index_Constant (Index, Index_Con);
11274             Set_Discriminal_Link     (Index_Con, Index);
11275
11276             --  Retrieve the bounds of the entry family
11277
11278             High := Type_High_Bound (Etype (Index));
11279             Low  := Type_Low_Bound  (Etype (Index));
11280
11281             --  In the simple case the entry family is given by a subtype
11282             --  mark and the index constant has the same type.
11283
11284             if Is_Entity_Name (Original_Node (
11285                  Discrete_Subtype_Definition (Parent (Index))))
11286             then
11287                Index_Typ := Etype (Index);
11288
11289             --  Otherwise a new subtype declaration is required
11290
11291             else
11292                High := Replace_Bound (High);
11293                Low  := Replace_Bound (Low);
11294
11295                Index_Typ :=
11296                  Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
11297
11298                --  Generate:
11299                --    subtype Jnn is <Etype of Index> range Low .. High;
11300
11301                Decl :=
11302                  Make_Subtype_Declaration (Loc,
11303                    Defining_Identifier => Index_Typ,
11304                    Subtype_Indication =>
11305                      Make_Subtype_Indication (Loc,
11306                        Subtype_Mark =>
11307                          New_Reference_To (Base_Type (Etype (Index)), Loc),
11308                        Constraint =>
11309                          Make_Range_Constraint (Loc,
11310                            Range_Expression =>
11311                              Make_Range (Loc, Low, High))));
11312                Add (Decl);
11313             end if;
11314
11315             Set_Etype (Index_Con, Index_Typ);
11316
11317             --  Create the object which designates the index:
11318             --    J : constant Jnn :=
11319             --          Jnn'Val (_E - <index expr> + Jnn'Pos (Jnn'First));
11320             --
11321             --  where Jnn is the subtype created above or the original type of
11322             --  the index, _E is a formal of the protected body subprogram and
11323             --  <index expr> is the index of the first family member.
11324
11325             Decl :=
11326               Make_Object_Declaration (Loc,
11327                 Defining_Identifier => Index_Con,
11328                 Constant_Present => True,
11329                 Object_Definition =>
11330                   New_Reference_To (Index_Typ, Loc),
11331
11332                 Expression =>
11333                   Make_Attribute_Reference (Loc,
11334                     Prefix =>
11335                       New_Reference_To (Index_Typ, Loc),
11336                     Attribute_Name => Name_Val,
11337
11338                     Expressions => New_List (
11339
11340                       Make_Op_Add (Loc,
11341                         Left_Opnd =>
11342                           Make_Op_Subtract (Loc,
11343                             Left_Opnd =>
11344                               New_Reference_To (E, Loc),
11345                             Right_Opnd =>
11346                               Entry_Index_Expression (Loc,
11347                                 Defining_Identifier (Body_Nod),
11348                                 Empty, Conc_Typ)),
11349
11350                         Right_Opnd =>
11351                           Make_Attribute_Reference (Loc,
11352                             Prefix =>
11353                               New_Reference_To (Index_Typ, Loc),
11354                             Attribute_Name => Name_Pos,
11355                             Expressions => New_List (
11356                               Make_Attribute_Reference (Loc,
11357                                 Prefix =>
11358                                   New_Reference_To (Index_Typ, Loc),
11359                                 Attribute_Name => Name_First)))))));
11360             Add (Decl);
11361          end;
11362       end if;
11363    end Install_Private_Data_Declarations;
11364
11365    ---------------------------------
11366    -- Is_Potentially_Large_Family --
11367    ---------------------------------
11368
11369    function Is_Potentially_Large_Family
11370      (Base_Index : Entity_Id;
11371       Conctyp    : Entity_Id;
11372       Lo         : Node_Id;
11373       Hi         : Node_Id) return Boolean
11374    is
11375    begin
11376       return Scope (Base_Index) = Standard_Standard
11377         and then Base_Index = Base_Type (Standard_Integer)
11378         and then Has_Discriminants (Conctyp)
11379         and then Present
11380           (Discriminant_Default_Value (First_Discriminant (Conctyp)))
11381         and then
11382           (Denotes_Discriminant (Lo, True)
11383             or else Denotes_Discriminant (Hi, True));
11384    end Is_Potentially_Large_Family;
11385
11386    -------------------------------------
11387    -- Is_Private_Primitive_Subprogram --
11388    -------------------------------------
11389
11390    function Is_Private_Primitive_Subprogram (Id : Entity_Id) return Boolean is
11391    begin
11392       return
11393         (Ekind (Id) = E_Function or else Ekind (Id) = E_Procedure)
11394           and then Is_Private_Primitive (Id);
11395    end Is_Private_Primitive_Subprogram;
11396
11397    ------------------
11398    -- Index_Object --
11399    ------------------
11400
11401    function Index_Object (Spec_Id : Entity_Id) return Entity_Id is
11402       Bod_Subp : constant Entity_Id := Protected_Body_Subprogram (Spec_Id);
11403       Formal   : Entity_Id;
11404
11405    begin
11406       Formal := First_Formal (Bod_Subp);
11407       while Present (Formal) loop
11408
11409          --  Look for formal parameter _E
11410
11411          if Chars (Formal) = Name_uE then
11412             return Formal;
11413          end if;
11414
11415          Next_Formal (Formal);
11416       end loop;
11417
11418       --  A protected body subprogram should always have the parameter in
11419       --  question.
11420
11421       raise Program_Error;
11422    end Index_Object;
11423
11424    --------------------------------
11425    -- Make_Initialize_Protection --
11426    --------------------------------
11427
11428    function Make_Initialize_Protection
11429      (Protect_Rec : Entity_Id) return List_Id
11430    is
11431       Loc         : constant Source_Ptr := Sloc (Protect_Rec);
11432       P_Arr       : Entity_Id;
11433       Pdef        : Node_Id;
11434       Pdec        : Node_Id;
11435       Ptyp        : constant Node_Id :=
11436                       Corresponding_Concurrent_Type (Protect_Rec);
11437       Args        : List_Id;
11438       L           : constant List_Id := New_List;
11439       Has_Entry   : constant Boolean := Has_Entries (Ptyp);
11440       Restricted  : constant Boolean := Restricted_Profile;
11441
11442    begin
11443       --  We may need two calls to properly initialize the object, one to
11444       --  Initialize_Protection, and possibly one to Install_Handlers if we
11445       --  have a pragma Attach_Handler.
11446
11447       --  Get protected declaration. In the case of a task type declaration,
11448       --  this is simply the parent of the protected type entity. In the single
11449       --  protected object declaration, this parent will be the implicit type,
11450       --  and we can find the corresponding single protected object declaration
11451       --  by searching forward in the declaration list in the tree.
11452
11453       --  Is the test for N_Single_Protected_Declaration needed here??? Nodes
11454       --  of this type should have been removed during semantic analysis.
11455
11456       Pdec := Parent (Ptyp);
11457       while not Nkind_In (Pdec, N_Protected_Type_Declaration,
11458                                 N_Single_Protected_Declaration)
11459       loop
11460          Next (Pdec);
11461       end loop;
11462
11463       --  Now we can find the object definition from this declaration
11464
11465       Pdef := Protected_Definition (Pdec);
11466
11467       --  Build the parameter list for the call. Note that _Init is the name
11468       --  of the formal for the object to be initialized, which is the task
11469       --  value record itself.
11470
11471       Args := New_List;
11472
11473       --  Object parameter. This is a pointer to the object of type
11474       --  Protection used by the GNARL to control the protected object.
11475
11476       Append_To (Args,
11477         Make_Attribute_Reference (Loc,
11478           Prefix =>
11479             Make_Selected_Component (Loc,
11480               Prefix => Make_Identifier (Loc, Name_uInit),
11481               Selector_Name => Make_Identifier (Loc, Name_uObject)),
11482           Attribute_Name => Name_Unchecked_Access));
11483
11484       --  Priority parameter. Set to Unspecified_Priority unless there is a
11485       --  priority pragma, in which case we take the value from the pragma,
11486       --  or there is an interrupt pragma and no priority pragma, and we
11487       --  set the ceiling to Interrupt_Priority'Last, an implementation-
11488       --  defined value, see D.3(10).
11489
11490       if Present (Pdef)
11491         and then Has_Priority_Pragma (Pdef)
11492       then
11493          declare
11494             Prio : constant Node_Id :=
11495                      Expression
11496                        (First
11497                           (Pragma_Argument_Associations
11498                              (Find_Task_Or_Protected_Pragma
11499                                 (Pdef, Name_Priority))));
11500             Temp : Entity_Id;
11501
11502          begin
11503             --  If priority is a static expression, then we can duplicate it
11504             --  with no problem and simply append it to the argument list.
11505
11506             if Is_Static_Expression (Prio) then
11507                Append_To (Args,
11508                           Duplicate_Subexpr_No_Checks (Prio));
11509
11510             --  Otherwise, the priority may be a per-object expression, if it
11511             --  depends on a discriminant of the type. In this case, create
11512             --  local variable to capture the expression. Note that it is
11513             --  really necessary to create this variable explicitly. It might
11514             --  be thought that removing side effects would the appropriate
11515             --  approach, but that could generate declarations improperly
11516             --  placed in the enclosing scope.
11517
11518             --  Note: Use System.Any_Priority as the expected type for the
11519             --  non-static priority expression, in case the expression has not
11520             --  been analyzed yet (as occurs for example with pragma
11521             --  Interrupt_Priority).
11522
11523             else
11524                Temp :=
11525                  Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
11526
11527                Append_To (L,
11528                   Make_Object_Declaration (Loc,
11529                      Defining_Identifier => Temp,
11530                      Object_Definition   =>
11531                        New_Occurrence_Of (RTE (RE_Any_Priority), Loc),
11532                      Expression          => Relocate_Node (Prio)));
11533
11534                   Append_To (Args, New_Occurrence_Of (Temp, Loc));
11535             end if;
11536          end;
11537
11538       --  When no priority is specified but an xx_Handler pragma is, we default
11539       --  to System.Interrupts.Default_Interrupt_Priority, see D.3(10).
11540
11541       elsif Has_Interrupt_Handler (Ptyp)
11542         or else Has_Attach_Handler (Ptyp)
11543       then
11544          Append_To (Args,
11545            New_Reference_To (RTE (RE_Default_Interrupt_Priority), Loc));
11546
11547       --  Normal case, no priority or xx_Handler specified, default priority
11548
11549       else
11550          Append_To (Args,
11551            New_Reference_To (RTE (RE_Unspecified_Priority), Loc));
11552       end if;
11553
11554       --  Test for Compiler_Info parameter. This parameter allows entry body
11555       --  procedures and barrier functions to be called from the runtime. It
11556       --  is a pointer to the record generated by the compiler to represent
11557       --  the protected object.
11558
11559       if Has_Entry
11560         or else Has_Interrupt_Handler (Ptyp)
11561         or else Has_Attach_Handler (Ptyp)
11562         or else Has_Interfaces (Protect_Rec)
11563       then
11564          declare
11565             Pkg_Id      : constant RTU_Id  :=
11566                             Corresponding_Runtime_Package (Ptyp);
11567             Called_Subp : RE_Id;
11568
11569          begin
11570             case Pkg_Id is
11571                when System_Tasking_Protected_Objects_Entries =>
11572                   Called_Subp := RE_Initialize_Protection_Entries;
11573
11574                when System_Tasking_Protected_Objects =>
11575                   Called_Subp := RE_Initialize_Protection;
11576
11577                when System_Tasking_Protected_Objects_Single_Entry =>
11578                   Called_Subp := RE_Initialize_Protection_Entry;
11579
11580                when others =>
11581                   raise Program_Error;
11582             end case;
11583
11584             if Has_Entry or else not Restricted then
11585                Append_To (Args,
11586                  Make_Attribute_Reference (Loc,
11587                    Prefix => Make_Identifier (Loc, Name_uInit),
11588                    Attribute_Name => Name_Address));
11589             end if;
11590
11591             --  Entry_Bodies parameter. This is a pointer to an array of
11592             --  pointers to the entry body procedures and barrier functions of
11593             --  the object. If the protected type has no entries this object
11594             --  will not exist, in this case, pass a null.
11595
11596             if Has_Entry then
11597                P_Arr := Entry_Bodies_Array (Ptyp);
11598
11599                Append_To (Args,
11600                  Make_Attribute_Reference (Loc,
11601                    Prefix => New_Reference_To (P_Arr, Loc),
11602                    Attribute_Name => Name_Unrestricted_Access));
11603
11604                if Pkg_Id = System_Tasking_Protected_Objects_Entries then
11605
11606                   --  Find index mapping function (clumsy but ok for now)
11607
11608                   while Ekind (P_Arr) /= E_Function loop
11609                      Next_Entity (P_Arr);
11610                   end loop;
11611
11612                   Append_To (Args,
11613                     Make_Attribute_Reference (Loc,
11614                       Prefix =>
11615                         New_Reference_To (P_Arr, Loc),
11616                       Attribute_Name => Name_Unrestricted_Access));
11617
11618                   --  Build_Entry_Names generation flag. When set to true, the
11619                   --  runtime will allocate an array to hold the string names
11620                   --  of protected entries.
11621
11622                   if not Restricted_Profile then
11623                      if Entry_Names_OK then
11624                         Append_To (Args,
11625                           New_Reference_To (Standard_True, Loc));
11626                      else
11627                         Append_To (Args,
11628                           New_Reference_To (Standard_False, Loc));
11629                      end if;
11630                   end if;
11631                end if;
11632
11633             elsif Pkg_Id = System_Tasking_Protected_Objects_Single_Entry then
11634                Append_To (Args, Make_Null (Loc));
11635
11636             elsif Pkg_Id = System_Tasking_Protected_Objects_Entries then
11637                Append_To (Args, Make_Null (Loc));
11638                Append_To (Args, Make_Null (Loc));
11639                Append_To (Args, New_Reference_To (Standard_False, Loc));
11640             end if;
11641
11642             Append_To (L,
11643               Make_Procedure_Call_Statement (Loc,
11644                 Name => New_Reference_To (RTE (Called_Subp), Loc),
11645                 Parameter_Associations => Args));
11646          end;
11647       else
11648          Append_To (L,
11649            Make_Procedure_Call_Statement (Loc,
11650              Name => New_Reference_To (RTE (RE_Initialize_Protection), Loc),
11651              Parameter_Associations => Args));
11652       end if;
11653
11654       if Has_Attach_Handler (Ptyp) then
11655
11656          --  We have a list of N Attach_Handler (ProcI, ExprI), and we have to
11657          --  make the following call:
11658
11659          --  Install_Handlers (_object,
11660          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
11661
11662          --  or, in the case of Ravenscar:
11663
11664          --  Install_Restricted_Handlers
11665          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
11666
11667          declare
11668             Args  : constant List_Id := New_List;
11669             Table : constant List_Id := New_List;
11670             Ritem : Node_Id          := First_Rep_Item (Ptyp);
11671
11672          begin
11673             --  Build the Attach_Handler table argument
11674
11675             while Present (Ritem) loop
11676                if Nkind (Ritem) = N_Pragma
11677                  and then Pragma_Name (Ritem) = Name_Attach_Handler
11678                then
11679                   declare
11680                      Handler : constant Node_Id :=
11681                                  First (Pragma_Argument_Associations (Ritem));
11682
11683                      Interrupt : constant Node_Id := Next (Handler);
11684                      Expr      : constant Node_Id := Expression (Interrupt);
11685
11686                   begin
11687                      Append_To (Table,
11688                        Make_Aggregate (Loc, Expressions => New_List (
11689                          Unchecked_Convert_To
11690                           (RTE (RE_System_Interrupt_Id), Expr),
11691                          Make_Attribute_Reference (Loc,
11692                            Prefix => Make_Selected_Component (Loc,
11693                               Make_Identifier (Loc, Name_uInit),
11694                               Duplicate_Subexpr_No_Checks
11695                                 (Expression (Handler))),
11696                            Attribute_Name => Name_Access))));
11697                   end;
11698                end if;
11699
11700                Next_Rep_Item (Ritem);
11701             end loop;
11702
11703             --  Append the table argument we just built
11704
11705             Append_To (Args, Make_Aggregate (Loc, Table));
11706
11707             --  Append the Install_Handlers (or Install_Restricted_Handlers)
11708             --  call to the statements.
11709
11710             if Restricted then
11711                --  Call a simplified version of Install_Handlers to be used
11712                --  when the Ravenscar restrictions are in effect
11713                --  (Install_Restricted_Handlers).
11714
11715                Append_To (L,
11716                  Make_Procedure_Call_Statement (Loc,
11717                    Name =>
11718                      New_Reference_To
11719                         (RTE (RE_Install_Restricted_Handlers), Loc),
11720                    Parameter_Associations => Args));
11721
11722             else
11723                --  First, prepends the _object argument
11724
11725                Prepend_To (Args,
11726                  Make_Attribute_Reference (Loc,
11727                    Prefix =>
11728                      Make_Selected_Component (Loc,
11729                        Prefix => Make_Identifier (Loc, Name_uInit),
11730                        Selector_Name => Make_Identifier (Loc, Name_uObject)),
11731                    Attribute_Name => Name_Unchecked_Access));
11732
11733                --  Then, insert call to Install_Handlers
11734
11735                Append_To (L,
11736                  Make_Procedure_Call_Statement (Loc,
11737                    Name => New_Reference_To (RTE (RE_Install_Handlers), Loc),
11738                    Parameter_Associations => Args));
11739             end if;
11740          end;
11741       end if;
11742
11743       return L;
11744    end Make_Initialize_Protection;
11745
11746    ---------------------------
11747    -- Make_Task_Create_Call --
11748    ---------------------------
11749
11750    function Make_Task_Create_Call (Task_Rec : Entity_Id) return Node_Id is
11751       Loc    : constant Source_Ptr := Sloc (Task_Rec);
11752       Args   : List_Id;
11753       Ecount : Node_Id;
11754       Name   : Node_Id;
11755       Tdec   : Node_Id;
11756       Tdef   : Node_Id;
11757       Tnam   : Name_Id;
11758       Ttyp   : Node_Id;
11759
11760    begin
11761       Ttyp := Corresponding_Concurrent_Type (Task_Rec);
11762       Tnam := Chars (Ttyp);
11763
11764       --  Get task declaration. In the case of a task type declaration, this is
11765       --  simply the parent of the task type entity. In the single task
11766       --  declaration, this parent will be the implicit type, and we can find
11767       --  the corresponding single task declaration by searching forward in the
11768       --  declaration list in the tree.
11769
11770       --  Is the test for N_Single_Task_Declaration needed here??? Nodes of
11771       --  this type should have been removed during semantic analysis.
11772
11773       Tdec := Parent (Ttyp);
11774       while not Nkind_In (Tdec, N_Task_Type_Declaration,
11775                                 N_Single_Task_Declaration)
11776       loop
11777          Next (Tdec);
11778       end loop;
11779
11780       --  Now we can find the task definition from this declaration
11781
11782       Tdef := Task_Definition (Tdec);
11783
11784       --  Build the parameter list for the call. Note that _Init is the name
11785       --  of the formal for the object to be initialized, which is the task
11786       --  value record itself.
11787
11788       Args := New_List;
11789
11790       --  Priority parameter. Set to Unspecified_Priority unless there is a
11791       --  priority pragma, in which case we take the value from the pragma.
11792
11793       if Present (Tdef) and then Has_Priority_Pragma (Tdef) then
11794          Append_To (Args,
11795            Make_Selected_Component (Loc,
11796              Prefix => Make_Identifier (Loc, Name_uInit),
11797              Selector_Name => Make_Identifier (Loc, Name_uPriority)));
11798       else
11799          Append_To (Args,
11800            New_Reference_To (RTE (RE_Unspecified_Priority), Loc));
11801       end if;
11802
11803       --  Optional Stack parameter
11804
11805       if Restricted_Profile then
11806
11807          --  If the stack has been preallocated by the expander then
11808          --  pass its address. Otherwise, pass a null address.
11809
11810          if Preallocated_Stacks_On_Target then
11811             Append_To (Args,
11812               Make_Attribute_Reference (Loc,
11813                 Prefix         => Make_Selected_Component (Loc,
11814                   Prefix        => Make_Identifier (Loc, Name_uInit),
11815                   Selector_Name =>
11816                     Make_Identifier (Loc, Name_uStack)),
11817                 Attribute_Name => Name_Address));
11818
11819          else
11820             Append_To (Args,
11821               New_Reference_To (RTE (RE_Null_Address), Loc));
11822          end if;
11823       end if;
11824
11825       --  Size parameter. If no Storage_Size pragma is present, then
11826       --  the size is taken from the taskZ variable for the type, which
11827       --  is either Unspecified_Size, or has been reset by the use of
11828       --  a Storage_Size attribute definition clause. If a pragma is
11829       --  present, then the size is taken from the _Size field of the
11830       --  task value record, which was set from the pragma value.
11831
11832       if Present (Tdef)
11833         and then Has_Storage_Size_Pragma (Tdef)
11834       then
11835          Append_To (Args,
11836            Make_Selected_Component (Loc,
11837              Prefix => Make_Identifier (Loc, Name_uInit),
11838              Selector_Name => Make_Identifier (Loc, Name_uSize)));
11839
11840       else
11841          Append_To (Args,
11842            New_Reference_To (Storage_Size_Variable (Ttyp), Loc));
11843       end if;
11844
11845       --  Task_Info parameter. Set to Unspecified_Task_Info unless there is a
11846       --  Task_Info pragma, in which case we take the value from the pragma.
11847
11848       if Present (Tdef)
11849         and then Has_Task_Info_Pragma (Tdef)
11850       then
11851          Append_To (Args,
11852            Make_Selected_Component (Loc,
11853              Prefix => Make_Identifier (Loc, Name_uInit),
11854              Selector_Name => Make_Identifier (Loc, Name_uTask_Info)));
11855
11856       else
11857          Append_To (Args,
11858            New_Reference_To (RTE (RE_Unspecified_Task_Info), Loc));
11859       end if;
11860
11861       if not Restricted_Profile then
11862
11863          --  Deadline parameter. If no Relative_Deadline pragma is present,
11864          --  then the deadline is Time_Span_Zero. If a pragma is present, then
11865          --  the deadline is taken from the _Relative_Deadline field of the
11866          --  task value record, which was set from the pragma value. Note that
11867          --  this parameter must not be generated for the restricted profiles
11868          --  since Ravenscar does not allow deadlines.
11869
11870          --  Case where pragma Relative_Deadline applies: use given value
11871
11872          if Present (Tdef) and then Has_Relative_Deadline_Pragma (Tdef) then
11873             Append_To (Args,
11874               Make_Selected_Component (Loc,
11875                 Prefix => Make_Identifier (Loc, Name_uInit),
11876                 Selector_Name =>
11877                   Make_Identifier (Loc, Name_uRelative_Deadline)));
11878
11879          --  No pragma Relative_Deadline apply to the task
11880
11881          else
11882             Append_To (Args,
11883               New_Reference_To (RTE (RE_Time_Span_Zero), Loc));
11884          end if;
11885
11886          --  Number of entries. This is an expression of the form:
11887
11888          --    n + _Init.a'Length + _Init.a'B'Length + ...
11889
11890          --  where a,b... are the entry family names for the task definition
11891
11892          Ecount :=
11893            Build_Entry_Count_Expression
11894              (Ttyp,
11895               Component_Items
11896                 (Component_List
11897                    (Type_Definition
11898                       (Parent (Corresponding_Record_Type (Ttyp))))),
11899               Loc);
11900          Append_To (Args, Ecount);
11901
11902          --  Master parameter. This is a reference to the _Master parameter of
11903          --  the initialization procedure, except in the case of the pragma
11904          --  Restrictions (No_Task_Hierarchy) where the value is fixed to 3.
11905          --  See comments in System.Tasking.Initialization.Init_RTS for the
11906          --  value 3.
11907
11908          if Restriction_Active (No_Task_Hierarchy) = False then
11909             Append_To (Args, Make_Identifier (Loc, Name_uMaster));
11910          else
11911             Append_To (Args, Make_Integer_Literal (Loc, 3));
11912          end if;
11913       end if;
11914
11915       --  State parameter. This is a pointer to the task body procedure. The
11916       --  required value is obtained by taking 'Unrestricted_Access of the task
11917       --  body procedure and converting it (with an unchecked conversion) to
11918       --  the type required by the task kernel. For further details, see the
11919       --  description of Expand_N_Task_Body. We use 'Unrestricted_Access rather
11920       --  than 'Address in order to avoid creating trampolines.
11921
11922       declare
11923          Body_Proc    : constant Node_Id := Get_Task_Body_Procedure (Ttyp);
11924          Subp_Ptr_Typ : constant Node_Id :=
11925                           Create_Itype (E_Access_Subprogram_Type, Tdec);
11926          Ref          : constant Node_Id := Make_Itype_Reference (Loc);
11927
11928       begin
11929          Set_Directly_Designated_Type (Subp_Ptr_Typ, Body_Proc);
11930          Set_Etype (Subp_Ptr_Typ, Subp_Ptr_Typ);
11931
11932          --  Be sure to freeze a reference to the access-to-subprogram type,
11933          --  otherwise gigi will complain that it's in the wrong scope, because
11934          --  it's actually inside the init procedure for the record type that
11935          --  corresponds to the task type.
11936
11937          --  This processing is causing a crash in the .NET/JVM back ends that
11938          --  is not yet understood, so skip it in these cases ???
11939
11940          if VM_Target = No_VM then
11941             Set_Itype (Ref, Subp_Ptr_Typ);
11942             Append_Freeze_Action (Task_Rec, Ref);
11943
11944             Append_To (Args,
11945               Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
11946                 Make_Qualified_Expression (Loc,
11947                   Subtype_Mark => New_Reference_To (Subp_Ptr_Typ, Loc),
11948                   Expression   =>
11949                     Make_Attribute_Reference (Loc,
11950                       Prefix =>
11951                         New_Occurrence_Of (Body_Proc, Loc),
11952                       Attribute_Name => Name_Unrestricted_Access))));
11953
11954          --  For the .NET/JVM cases revert to the original code below ???
11955
11956          else
11957             Append_To (Args,
11958               Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
11959                 Make_Attribute_Reference (Loc,
11960                   Prefix =>
11961                     New_Occurrence_Of (Body_Proc, Loc),
11962                   Attribute_Name => Name_Address)));
11963          end if;
11964       end;
11965
11966       --  Discriminants parameter. This is just the address of the task
11967       --  value record itself (which contains the discriminant values
11968
11969       Append_To (Args,
11970         Make_Attribute_Reference (Loc,
11971           Prefix => Make_Identifier (Loc, Name_uInit),
11972           Attribute_Name => Name_Address));
11973
11974       --  Elaborated parameter. This is an access to the elaboration Boolean
11975
11976       Append_To (Args,
11977         Make_Attribute_Reference (Loc,
11978           Prefix => Make_Identifier (Loc, New_External_Name (Tnam, 'E')),
11979           Attribute_Name => Name_Unchecked_Access));
11980
11981       --  Chain parameter. This is a reference to the _Chain parameter of
11982       --  the initialization procedure.
11983
11984       Append_To (Args, Make_Identifier (Loc, Name_uChain));
11985
11986       --  Task name parameter. Take this from the _Task_Id parameter to the
11987       --  init call unless there is a Task_Name pragma, in which case we take
11988       --  the value from the pragma.
11989
11990       if Present (Tdef)
11991         and then Has_Task_Name_Pragma (Tdef)
11992       then
11993          --  Copy expression in full, because it may be dynamic and have
11994          --  side effects.
11995
11996          Append_To (Args,
11997            New_Copy_Tree (
11998              Expression (First (
11999                Pragma_Argument_Associations (
12000                  Find_Task_Or_Protected_Pragma
12001                    (Tdef, Name_Task_Name))))));
12002
12003       else
12004          Append_To (Args, Make_Identifier (Loc, Name_uTask_Name));
12005       end if;
12006
12007       --  Created_Task parameter. This is the _Task_Id field of the task
12008       --  record value
12009
12010       Append_To (Args,
12011         Make_Selected_Component (Loc,
12012           Prefix => Make_Identifier (Loc, Name_uInit),
12013           Selector_Name => Make_Identifier (Loc, Name_uTask_Id)));
12014
12015       --  Build_Entry_Names generation flag. When set to true, the runtime
12016       --  will allocate an array to hold the string names of task entries.
12017
12018       if not Restricted_Profile then
12019          if Has_Entries (Ttyp)
12020            and then Entry_Names_OK
12021          then
12022             Append_To (Args, New_Reference_To (Standard_True, Loc));
12023          else
12024             Append_To (Args, New_Reference_To (Standard_False, Loc));
12025          end if;
12026       end if;
12027
12028       if Restricted_Profile then
12029          Name := New_Reference_To (RTE (RE_Create_Restricted_Task), Loc);
12030       else
12031          Name := New_Reference_To (RTE (RE_Create_Task), Loc);
12032       end if;
12033
12034       return
12035         Make_Procedure_Call_Statement (Loc,
12036           Name => Name,
12037           Parameter_Associations => Args);
12038    end Make_Task_Create_Call;
12039
12040    ------------------------------
12041    -- Next_Protected_Operation --
12042    ------------------------------
12043
12044    function Next_Protected_Operation (N : Node_Id) return Node_Id is
12045       Next_Op : Node_Id;
12046
12047    begin
12048       Next_Op := Next (N);
12049       while Present (Next_Op)
12050         and then not Nkind_In (Next_Op, N_Subprogram_Body, N_Entry_Body)
12051       loop
12052          Next (Next_Op);
12053       end loop;
12054
12055       return Next_Op;
12056    end Next_Protected_Operation;
12057
12058    ---------------------
12059    -- Null_Statements --
12060    ---------------------
12061
12062    function Null_Statements (Stats : List_Id) return Boolean is
12063       Stmt : Node_Id;
12064
12065    begin
12066       Stmt := First (Stats);
12067       while Nkind (Stmt) /= N_Empty
12068         and then (Nkind_In (Stmt, N_Null_Statement, N_Label)
12069                     or else
12070                       (Nkind (Stmt) = N_Pragma
12071                          and then (Pragma_Name (Stmt) = Name_Unreferenced
12072                                      or else
12073                                    Pragma_Name (Stmt) = Name_Unmodified
12074                                      or else
12075                                    Pragma_Name (Stmt) = Name_Warnings)))
12076       loop
12077          Next (Stmt);
12078       end loop;
12079
12080       return Nkind (Stmt) = N_Empty;
12081    end Null_Statements;
12082
12083    --------------------------
12084    -- Parameter_Block_Pack --
12085    --------------------------
12086
12087    function Parameter_Block_Pack
12088      (Loc     : Source_Ptr;
12089       Blk_Typ : Entity_Id;
12090       Actuals : List_Id;
12091       Formals : List_Id;
12092       Decls   : List_Id;
12093       Stmts   : List_Id) return Node_Id
12094    is
12095       Actual    : Entity_Id;
12096       Expr      : Node_Id := Empty;
12097       Formal    : Entity_Id;
12098       Has_Param : Boolean := False;
12099       P         : Entity_Id;
12100       Params    : List_Id;
12101       Temp_Asn  : Node_Id;
12102       Temp_Nam  : Node_Id;
12103
12104    begin
12105       Actual := First (Actuals);
12106       Formal := Defining_Identifier (First (Formals));
12107       Params := New_List;
12108
12109       while Present (Actual) loop
12110          if Is_By_Copy_Type (Etype (Actual)) then
12111             --  Generate:
12112             --    Jnn : aliased <formal-type>
12113
12114             Temp_Nam :=
12115               Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
12116
12117             Append_To (Decls,
12118               Make_Object_Declaration (Loc,
12119                 Aliased_Present =>
12120                   True,
12121                 Defining_Identifier =>
12122                   Temp_Nam,
12123                 Object_Definition =>
12124                   New_Reference_To (Etype (Formal), Loc)));
12125
12126             if Ekind (Formal) /= E_Out_Parameter then
12127
12128                --  Generate:
12129                --    Jnn := <actual>
12130
12131                Temp_Asn :=
12132                  New_Reference_To (Temp_Nam, Loc);
12133
12134                Set_Assignment_OK (Temp_Asn);
12135
12136                Append_To (Stmts,
12137                  Make_Assignment_Statement (Loc,
12138                    Name =>
12139                      Temp_Asn,
12140                    Expression =>
12141                      New_Copy_Tree (Actual)));
12142             end if;
12143
12144             --  Generate:
12145             --    Jnn'unchecked_access
12146
12147             Append_To (Params,
12148               Make_Attribute_Reference (Loc,
12149                 Attribute_Name =>
12150                   Name_Unchecked_Access,
12151                 Prefix =>
12152                   New_Reference_To (Temp_Nam, Loc)));
12153
12154             Has_Param := True;
12155
12156          --  The controlling parameter is omitted
12157
12158          else
12159             if not Is_Controlling_Actual (Actual) then
12160                Append_To (Params,
12161                  Make_Reference (Loc, New_Copy_Tree (Actual)));
12162
12163                Has_Param := True;
12164             end if;
12165          end if;
12166
12167          Next_Actual (Actual);
12168          Next_Formal_With_Extras (Formal);
12169       end loop;
12170
12171       if Has_Param then
12172          Expr := Make_Aggregate (Loc, Params);
12173       end if;
12174
12175       --  Generate:
12176       --    P : Ann := (
12177       --      J1'unchecked_access;
12178       --      <actual2>'reference;
12179       --      ...);
12180
12181       P := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
12182
12183       Append_To (Decls,
12184         Make_Object_Declaration (Loc,
12185           Defining_Identifier =>
12186             P,
12187           Object_Definition =>
12188             New_Reference_To (Blk_Typ, Loc),
12189           Expression =>
12190             Expr));
12191
12192       return P;
12193    end Parameter_Block_Pack;
12194
12195    ----------------------------
12196    -- Parameter_Block_Unpack --
12197    ----------------------------
12198
12199    function Parameter_Block_Unpack
12200      (Loc     : Source_Ptr;
12201       P       : Entity_Id;
12202       Actuals : List_Id;
12203       Formals : List_Id) return List_Id
12204    is
12205       Actual    : Entity_Id;
12206       Asnmt     : Node_Id;
12207       Formal    : Entity_Id;
12208       Has_Asnmt : Boolean := False;
12209       Result    : constant List_Id := New_List;
12210
12211    begin
12212       Actual := First (Actuals);
12213       Formal := Defining_Identifier (First (Formals));
12214       while Present (Actual) loop
12215          if Is_By_Copy_Type (Etype (Actual))
12216            and then Ekind (Formal) /= E_In_Parameter
12217          then
12218             --  Generate:
12219             --    <actual> := P.<formal>;
12220
12221             Asnmt :=
12222               Make_Assignment_Statement (Loc,
12223                 Name =>
12224                   New_Copy (Actual),
12225                 Expression =>
12226                   Make_Explicit_Dereference (Loc,
12227                     Make_Selected_Component (Loc,
12228                       Prefix =>
12229                         New_Reference_To (P, Loc),
12230                       Selector_Name =>
12231                         Make_Identifier (Loc, Chars (Formal)))));
12232
12233             Set_Assignment_OK (Name (Asnmt));
12234             Append_To (Result, Asnmt);
12235
12236             Has_Asnmt := True;
12237          end if;
12238
12239          Next_Actual (Actual);
12240          Next_Formal_With_Extras (Formal);
12241       end loop;
12242
12243       if Has_Asnmt then
12244          return Result;
12245       else
12246          return New_List (Make_Null_Statement (Loc));
12247       end if;
12248    end Parameter_Block_Unpack;
12249
12250    ----------------------
12251    -- Set_Discriminals --
12252    ----------------------
12253
12254    procedure Set_Discriminals (Dec : Node_Id) is
12255       D       : Entity_Id;
12256       Pdef    : Entity_Id;
12257       D_Minal : Entity_Id;
12258
12259    begin
12260       pragma Assert (Nkind (Dec) = N_Protected_Type_Declaration);
12261       Pdef := Defining_Identifier (Dec);
12262
12263       if Has_Discriminants (Pdef) then
12264          D := First_Discriminant (Pdef);
12265          while Present (D) loop
12266             D_Minal :=
12267               Make_Defining_Identifier (Sloc (D),
12268                 Chars => New_External_Name (Chars (D), 'D'));
12269
12270             Set_Ekind (D_Minal, E_Constant);
12271             Set_Etype (D_Minal, Etype (D));
12272             Set_Scope (D_Minal, Pdef);
12273             Set_Discriminal (D, D_Minal);
12274             Set_Discriminal_Link (D_Minal, D);
12275
12276             Next_Discriminant (D);
12277          end loop;
12278       end if;
12279    end Set_Discriminals;
12280
12281    -----------------------
12282    -- Trivial_Accept_OK --
12283    -----------------------
12284
12285    function Trivial_Accept_OK return Boolean is
12286    begin
12287       case Opt.Task_Dispatching_Policy is
12288
12289          --  If we have the default task dispatching policy in effect, we can
12290          --  definitely do the optimization (one way of looking at this is to
12291          --  think of the formal definition of the default policy being allowed
12292          --  to run any task it likes after a rendezvous, so even if notionally
12293          --  a full rescheduling occurs, we can say that our dispatching policy
12294          --  (i.e. the default dispatching policy) reorders the queue to be the
12295          --  same as just before the call.
12296
12297          when ' ' =>
12298             return True;
12299
12300          --  FIFO_Within_Priorities certainly does not permit this
12301          --  optimization since the Rendezvous is a scheduling action that may
12302          --  require some other task to be run.
12303
12304          when 'F' =>
12305             return False;
12306
12307          --  For now, disallow the optimization for all other policies. This
12308          --  may be over-conservative, but it is certainly not incorrect.
12309
12310          when others =>
12311             return False;
12312
12313       end case;
12314    end Trivial_Accept_OK;
12315
12316 end Exp_Ch9;