OSDN Git Service

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