OSDN Git Service

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