OSDN Git Service

2009-10-28 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch9.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 9                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-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       if Comes_From_Source (T) then
3987          --  This is an explicit task type
3988          Spec_Id :=
3989            Make_Defining_Identifier (Loc,
3990              Chars => New_External_Name (Chars (T), "TB"));
3991       else
3992          --  This is an anonymous task type
3993          Spec_Id :=
3994            Make_Defining_Identifier (Loc,
3995              Chars => New_External_Name (Chars (T), 'B'));
3996       end if;
3997
3998       Set_Is_Internal (Spec_Id);
3999
4000       --  Associate the procedure with the task, if this is the declaration
4001       --  (and not the body) of the procedure.
4002
4003       if No (Task_Body_Procedure (T)) then
4004          Set_Task_Body_Procedure (T, Spec_Id);
4005       end if;
4006
4007       return
4008         Make_Procedure_Specification (Loc,
4009           Defining_Unit_Name       => Spec_Id,
4010           Parameter_Specifications => New_List (
4011             Make_Parameter_Specification (Loc,
4012               Defining_Identifier =>
4013                 Make_Defining_Identifier (Loc, Name_uTask),
4014               Parameter_Type      =>
4015                 Make_Access_Definition (Loc,
4016                   Subtype_Mark =>
4017                     New_Reference_To (Corresponding_Record_Type (T), Loc)))));
4018    end Build_Task_Proc_Specification;
4019
4020    ---------------------------------------
4021    -- Build_Unprotected_Subprogram_Body --
4022    ---------------------------------------
4023
4024    function Build_Unprotected_Subprogram_Body
4025      (N   : Node_Id;
4026       Pid : Node_Id) return Node_Id
4027    is
4028       Decls : constant List_Id := Declarations (N);
4029
4030    begin
4031       --  Add renamings for the Protection object, discriminals, privals and
4032       --  the entry index constant for use by debugger.
4033
4034       Debug_Private_Data_Declarations (Decls);
4035
4036       --  Make an unprotected version of the subprogram for use within the same
4037       --  object, with a new name and an additional parameter representing the
4038       --  object.
4039
4040       return
4041         Make_Subprogram_Body (Sloc (N),
4042           Specification              =>
4043             Build_Protected_Sub_Specification (N, Pid, Unprotected_Mode),
4044           Declarations               => Decls,
4045           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
4046    end Build_Unprotected_Subprogram_Body;
4047
4048    ----------------------------
4049    -- Collect_Entry_Families --
4050    ----------------------------
4051
4052    procedure Collect_Entry_Families
4053      (Loc          : Source_Ptr;
4054       Cdecls       : List_Id;
4055       Current_Node : in out Node_Id;
4056       Conctyp      : Entity_Id)
4057    is
4058       Efam      : Entity_Id;
4059       Efam_Decl : Node_Id;
4060       Efam_Type : Entity_Id;
4061
4062    begin
4063       Efam := First_Entity (Conctyp);
4064       while Present (Efam) loop
4065          if Ekind (Efam) = E_Entry_Family then
4066             Efam_Type :=
4067               Make_Defining_Identifier (Loc,
4068                 Chars => New_Internal_Name ('F'));
4069
4070             declare
4071                Bas : Entity_Id :=
4072                        Base_Type
4073                         (Etype (Discrete_Subtype_Definition (Parent (Efam))));
4074
4075                Bas_Decl : Node_Id := Empty;
4076                Lo, Hi   : Node_Id;
4077
4078             begin
4079                Get_Index_Bounds
4080                  (Discrete_Subtype_Definition (Parent (Efam)), Lo, Hi);
4081
4082                if Is_Potentially_Large_Family (Bas, Conctyp, Lo, Hi) then
4083                   Bas :=
4084                     Make_Defining_Identifier (Loc,
4085                       Chars => New_Internal_Name ('B'));
4086
4087                   Bas_Decl :=
4088                     Make_Subtype_Declaration (Loc,
4089                        Defining_Identifier => Bas,
4090                        Subtype_Indication  =>
4091                          Make_Subtype_Indication (Loc,
4092                            Subtype_Mark =>
4093                              New_Occurrence_Of (Standard_Integer, Loc),
4094                            Constraint   =>
4095                              Make_Range_Constraint (Loc,
4096                                Range_Expression => Make_Range (Loc,
4097                                  Make_Integer_Literal
4098                                    (Loc, -Entry_Family_Bound),
4099                                  Make_Integer_Literal
4100                                    (Loc, Entry_Family_Bound - 1)))));
4101
4102                   Insert_After (Current_Node, Bas_Decl);
4103                   Current_Node := Bas_Decl;
4104                   Analyze (Bas_Decl);
4105                end if;
4106
4107                Efam_Decl :=
4108                  Make_Full_Type_Declaration (Loc,
4109                    Defining_Identifier => Efam_Type,
4110                    Type_Definition =>
4111                      Make_Unconstrained_Array_Definition (Loc,
4112                        Subtype_Marks =>
4113                          (New_List (New_Occurrence_Of (Bas, Loc))),
4114
4115                     Component_Definition =>
4116                       Make_Component_Definition (Loc,
4117                         Aliased_Present    => False,
4118                         Subtype_Indication =>
4119                           New_Reference_To (Standard_Character, Loc))));
4120             end;
4121
4122             Insert_After (Current_Node, Efam_Decl);
4123             Current_Node := Efam_Decl;
4124             Analyze (Efam_Decl);
4125
4126             Append_To (Cdecls,
4127               Make_Component_Declaration (Loc,
4128                 Defining_Identifier =>
4129                   Make_Defining_Identifier (Loc, Chars (Efam)),
4130
4131                 Component_Definition =>
4132                   Make_Component_Definition (Loc,
4133                     Aliased_Present    => False,
4134                     Subtype_Indication =>
4135                       Make_Subtype_Indication (Loc,
4136                         Subtype_Mark =>
4137                           New_Occurrence_Of (Efam_Type, Loc),
4138
4139                         Constraint  =>
4140                           Make_Index_Or_Discriminant_Constraint (Loc,
4141                             Constraints => New_List (
4142                               New_Occurrence_Of
4143                                 (Etype (Discrete_Subtype_Definition
4144                                   (Parent (Efam))), Loc)))))));
4145
4146          end if;
4147
4148          Next_Entity (Efam);
4149       end loop;
4150    end Collect_Entry_Families;
4151
4152    -----------------------
4153    -- Concurrent_Object --
4154    -----------------------
4155
4156    function Concurrent_Object
4157      (Spec_Id  : Entity_Id;
4158       Conc_Typ : Entity_Id) return Entity_Id
4159    is
4160    begin
4161       --  Parameter _O or _object
4162
4163       if Is_Protected_Type (Conc_Typ) then
4164          return First_Formal (Protected_Body_Subprogram (Spec_Id));
4165
4166       --  Parameter _task
4167
4168       else
4169          pragma Assert (Is_Task_Type (Conc_Typ));
4170          return First_Formal (Task_Body_Procedure (Conc_Typ));
4171       end if;
4172    end Concurrent_Object;
4173
4174    ----------------------
4175    -- Copy_Result_Type --
4176    ----------------------
4177
4178    function Copy_Result_Type (Res : Node_Id) return Node_Id is
4179       New_Res  : constant Node_Id := New_Copy_Tree (Res);
4180       Par_Spec : Node_Id;
4181       Formal   : Entity_Id;
4182
4183    begin
4184       --  If the result type is an access_to_subprogram, we must create
4185       --  new entities for its spec.
4186
4187       if Nkind (New_Res) = N_Access_Definition
4188         and then Present (Access_To_Subprogram_Definition (New_Res))
4189       then
4190          --  Provide new entities for the formals
4191
4192          Par_Spec := First (Parameter_Specifications
4193                               (Access_To_Subprogram_Definition (New_Res)));
4194          while Present (Par_Spec) loop
4195             Formal := Defining_Identifier (Par_Spec);
4196             Set_Defining_Identifier (Par_Spec,
4197               Make_Defining_Identifier (Sloc (Formal), Chars (Formal)));
4198             Next (Par_Spec);
4199          end loop;
4200       end if;
4201
4202       return New_Res;
4203    end Copy_Result_Type;
4204
4205    --------------------
4206    -- Concurrent_Ref --
4207    --------------------
4208
4209    --  The expression returned for a reference to a concurrent object has the
4210    --  form:
4211
4212    --    taskV!(name)._Task_Id
4213
4214    --  for a task, and
4215
4216    --    objectV!(name)._Object
4217
4218    --  for a protected object. For the case of an access to a concurrent
4219    --  object, there is an extra explicit dereference:
4220
4221    --    taskV!(name.all)._Task_Id
4222    --    objectV!(name.all)._Object
4223
4224    --  here taskV and objectV are the types for the associated records, which
4225    --  contain the required _Task_Id and _Object fields for tasks and protected
4226    --  objects, respectively.
4227
4228    --  For the case of a task type name, the expression is
4229
4230    --    Self;
4231
4232    --  i.e. a call to the Self function which returns precisely this Task_Id
4233
4234    --  For the case of a protected type name, the expression is
4235
4236    --    objectR
4237
4238    --  which is a renaming of the _object field of the current object
4239    --  record, passed into protected operations as a parameter.
4240
4241    function Concurrent_Ref (N : Node_Id) return Node_Id is
4242       Loc  : constant Source_Ptr := Sloc (N);
4243       Ntyp : constant Entity_Id  := Etype (N);
4244       Dtyp : Entity_Id;
4245       Sel  : Name_Id;
4246
4247       function Is_Current_Task (T : Entity_Id) return Boolean;
4248       --  Check whether the reference is to the immediately enclosing task
4249       --  type, or to an outer one (rare but legal).
4250
4251       ---------------------
4252       -- Is_Current_Task --
4253       ---------------------
4254
4255       function Is_Current_Task (T : Entity_Id) return Boolean is
4256          Scop : Entity_Id;
4257
4258       begin
4259          Scop := Current_Scope;
4260          while Present (Scop)
4261            and then Scop /= Standard_Standard
4262          loop
4263
4264             if Scop = T then
4265                return True;
4266
4267             elsif Is_Task_Type (Scop) then
4268                return False;
4269
4270             --  If this is a procedure nested within the task type, we must
4271             --  assume that it can be called from an inner task, and therefore
4272             --  cannot treat it as a local reference.
4273
4274             elsif Is_Overloadable (Scop)
4275               and then In_Open_Scopes (T)
4276             then
4277                return False;
4278
4279             else
4280                Scop := Scope (Scop);
4281             end if;
4282          end loop;
4283
4284          --  We know that we are within the task body, so should have found it
4285          --  in scope.
4286
4287          raise Program_Error;
4288       end Is_Current_Task;
4289
4290    --  Start of processing for Concurrent_Ref
4291
4292    begin
4293       if Is_Access_Type (Ntyp) then
4294          Dtyp := Designated_Type (Ntyp);
4295
4296          if Is_Protected_Type (Dtyp) then
4297             Sel := Name_uObject;
4298          else
4299             Sel := Name_uTask_Id;
4300          end if;
4301
4302          return
4303            Make_Selected_Component (Loc,
4304              Prefix =>
4305                Unchecked_Convert_To (Corresponding_Record_Type (Dtyp),
4306                  Make_Explicit_Dereference (Loc, N)),
4307              Selector_Name => Make_Identifier (Loc, Sel));
4308
4309       elsif Is_Entity_Name (N)
4310         and then Is_Concurrent_Type (Entity (N))
4311       then
4312          if Is_Task_Type (Entity (N)) then
4313
4314             if Is_Current_Task (Entity (N)) then
4315                return
4316                  Make_Function_Call (Loc,
4317                    Name => New_Reference_To (RTE (RE_Self), Loc));
4318
4319             else
4320                declare
4321                   Decl   : Node_Id;
4322                   T_Self : constant Entity_Id :=
4323                              Make_Defining_Identifier (Loc,
4324                                Chars => New_Internal_Name ('T'));
4325                   T_Body : constant Node_Id :=
4326                              Parent (Corresponding_Body (Parent (Entity (N))));
4327
4328                begin
4329                   Decl := Make_Object_Declaration (Loc,
4330                      Defining_Identifier => T_Self,
4331                      Object_Definition =>
4332                        New_Occurrence_Of (RTE (RO_ST_Task_Id), Loc),
4333                      Expression =>
4334                        Make_Function_Call (Loc,
4335                          Name => New_Reference_To (RTE (RE_Self), Loc)));
4336                   Prepend (Decl, Declarations (T_Body));
4337                   Analyze (Decl);
4338                   Set_Scope (T_Self, Entity (N));
4339                   return New_Occurrence_Of (T_Self,  Loc);
4340                end;
4341             end if;
4342
4343          else
4344             pragma Assert (Is_Protected_Type (Entity (N)));
4345
4346             return
4347               New_Reference_To (Find_Protection_Object (Current_Scope), Loc);
4348          end if;
4349
4350       else
4351          if Is_Protected_Type (Ntyp) then
4352             Sel := Name_uObject;
4353
4354          elsif Is_Task_Type (Ntyp) then
4355             Sel := Name_uTask_Id;
4356
4357          else
4358             raise Program_Error;
4359          end if;
4360
4361          return
4362            Make_Selected_Component (Loc,
4363              Prefix =>
4364                Unchecked_Convert_To (Corresponding_Record_Type (Ntyp),
4365                  New_Copy_Tree (N)),
4366              Selector_Name => Make_Identifier (Loc, Sel));
4367       end if;
4368    end Concurrent_Ref;
4369
4370    ------------------------
4371    -- Convert_Concurrent --
4372    ------------------------
4373
4374    function Convert_Concurrent
4375      (N   : Node_Id;
4376       Typ : Entity_Id) return Node_Id
4377    is
4378    begin
4379       if not Is_Concurrent_Type (Typ) then
4380          return N;
4381       else
4382          return
4383            Unchecked_Convert_To
4384              (Corresponding_Record_Type (Typ), New_Copy_Tree (N));
4385       end if;
4386    end Convert_Concurrent;
4387
4388    -------------------------------------
4389    -- Debug_Private_Data_Declarations --
4390    -------------------------------------
4391
4392    procedure Debug_Private_Data_Declarations (Decls : List_Id) is
4393       Debug_Nod : Node_Id;
4394       Decl      : Node_Id;
4395
4396    begin
4397       Decl := First (Decls);
4398       while Present (Decl)
4399         and then not Comes_From_Source (Decl)
4400       loop
4401          --  Declaration for concurrent entity _object and its access type,
4402          --  along with the entry index subtype:
4403          --    type prot_typVP is access prot_typV;
4404          --    _object : prot_typVP := prot_typV (_O);
4405          --    subtype Jnn is <Type of Index> range Low .. High;
4406
4407          if Nkind_In (Decl, N_Full_Type_Declaration, N_Object_Declaration) then
4408             Set_Debug_Info_Needed (Defining_Identifier (Decl));
4409
4410          --  Declaration for the Protection object, discriminals, privals and
4411          --  entry index constant:
4412          --    conc_typR   : protection_typ renames _object._object;
4413          --    discr_nameD : discr_typ renames _object.discr_name;
4414          --    discr_nameD : discr_typ renames _task.discr_name;
4415          --    prival_name : comp_typ  renames _object.comp_name;
4416          --    J : constant Jnn :=
4417          --          Jnn'Val (_E - <Index expression> + Jnn'Pos (Jnn'First));
4418
4419          elsif Nkind (Decl) = N_Object_Renaming_Declaration then
4420             Set_Debug_Info_Needed (Defining_Identifier (Decl));
4421             Debug_Nod := Debug_Renaming_Declaration (Decl);
4422
4423             if Present (Debug_Nod) then
4424                Insert_After (Decl, Debug_Nod);
4425             end if;
4426          end if;
4427
4428          Next (Decl);
4429       end loop;
4430    end Debug_Private_Data_Declarations;
4431
4432    ----------------------------
4433    -- Entry_Index_Expression --
4434    ----------------------------
4435
4436    function Entry_Index_Expression
4437      (Sloc  : Source_Ptr;
4438       Ent   : Entity_Id;
4439       Index : Node_Id;
4440       Ttyp  : Entity_Id) return Node_Id
4441    is
4442       Expr : Node_Id;
4443       Num  : Node_Id;
4444       Lo   : Node_Id;
4445       Hi   : Node_Id;
4446       Prev : Entity_Id;
4447       S    : Node_Id;
4448
4449    begin
4450       --  The queues of entries and entry families appear in textual order in
4451       --  the associated record. The entry index is computed as the sum of the
4452       --  number of queues for all entries that precede the designated one, to
4453       --  which is added the index expression, if this expression denotes a
4454       --  member of a family.
4455
4456       --  The following is a place holder for the count of simple entries
4457
4458       Num := Make_Integer_Literal (Sloc, 1);
4459
4460       --  We construct an expression which is a series of addition operations.
4461       --  The first operand is the number of single entries that precede this
4462       --  one, the second operand is the index value relative to the start of
4463       --  the referenced family, and the remaining operands are the lengths of
4464       --  the entry families that precede this entry, i.e. the constructed
4465       --  expression is:
4466
4467       --    number_simple_entries +
4468       --      (s'pos (index-value) - s'pos (family'first)) + 1 +
4469       --      family'length + ...
4470
4471       --  where index-value is the given index value, and s is the index
4472       --  subtype (we have to use pos because the subtype might be an
4473       --  enumeration type preventing direct subtraction). Note that the task
4474       --  entry array is one-indexed.
4475
4476       --  The upper bound of the entry family may be a discriminant, so we
4477       --  retrieve the lower bound explicitly to compute offset, rather than
4478       --  using the index subtype which may mention a discriminant.
4479
4480       if Present (Index) then
4481          S := Etype (Discrete_Subtype_Definition (Declaration_Node (Ent)));
4482
4483          Expr :=
4484            Make_Op_Add (Sloc,
4485              Left_Opnd  => Num,
4486
4487              Right_Opnd =>
4488                Family_Offset (
4489                  Sloc,
4490                  Make_Attribute_Reference (Sloc,
4491                    Attribute_Name => Name_Pos,
4492                    Prefix => New_Reference_To (Base_Type (S), Sloc),
4493                    Expressions => New_List (Relocate_Node (Index))),
4494                  Type_Low_Bound (S),
4495                  Ttyp,
4496                  False));
4497       else
4498          Expr := Num;
4499       end if;
4500
4501       --  Now add lengths of preceding entries and entry families
4502
4503       Prev := First_Entity (Ttyp);
4504
4505       while Chars (Prev) /= Chars (Ent)
4506         or else (Ekind (Prev) /= Ekind (Ent))
4507         or else not Sem_Ch6.Type_Conformant (Ent, Prev)
4508       loop
4509          if Ekind (Prev) = E_Entry then
4510             Set_Intval (Num, Intval (Num) + 1);
4511
4512          elsif Ekind (Prev) = E_Entry_Family then
4513             S :=
4514               Etype (Discrete_Subtype_Definition (Declaration_Node (Prev)));
4515             Lo := Type_Low_Bound  (S);
4516             Hi := Type_High_Bound (S);
4517
4518             Expr :=
4519               Make_Op_Add (Sloc,
4520               Left_Opnd  => Expr,
4521               Right_Opnd => Family_Size (Sloc, Hi, Lo, Ttyp, False));
4522
4523          --  Other components are anonymous types to be ignored
4524
4525          else
4526             null;
4527          end if;
4528
4529          Next_Entity (Prev);
4530       end loop;
4531
4532       return Expr;
4533    end Entry_Index_Expression;
4534
4535    ---------------------------
4536    -- Establish_Task_Master --
4537    ---------------------------
4538
4539    procedure Establish_Task_Master (N : Node_Id) is
4540       Call : Node_Id;
4541    begin
4542       if Restriction_Active (No_Task_Hierarchy) = False then
4543          Call := Build_Runtime_Call (Sloc (N), RE_Enter_Master);
4544          Prepend_To (Declarations (N), Call);
4545          Analyze (Call);
4546       end if;
4547    end Establish_Task_Master;
4548
4549    --------------------------------
4550    -- Expand_Accept_Declarations --
4551    --------------------------------
4552
4553    --  Part of the expansion of an accept statement involves the creation of
4554    --  a declaration that can be referenced from the statement sequence of
4555    --  the accept:
4556
4557    --    Ann : Address;
4558
4559    --  This declaration is inserted immediately before the accept statement
4560    --  and it is important that it be inserted before the statements of the
4561    --  statement sequence are analyzed. Thus it would be too late to create
4562    --  this declaration in the Expand_N_Accept_Statement routine, which is
4563    --  why there is a separate procedure to be called directly from Sem_Ch9.
4564
4565    --  Ann is used to hold the address of the record containing the parameters
4566    --  (see Expand_N_Entry_Call for more details on how this record is built).
4567    --  References to the parameters do an unchecked conversion of this address
4568    --  to a pointer to the required record type, and then access the field that
4569    --  holds the value of the required parameter. The entity for the address
4570    --  variable is held as the top stack element (i.e. the last element) of the
4571    --  Accept_Address stack in the corresponding entry entity, and this element
4572    --  must be set in place  before the statements are processed.
4573
4574    --  The above description applies to the case of a stand alone accept
4575    --  statement, i.e. one not appearing as part of a select alternative.
4576
4577    --  For the case of an accept that appears as part of a select alternative
4578    --  of a selective accept, we must still create the declaration right away,
4579    --  since Ann is needed immediately, but there is an important difference:
4580
4581    --    The declaration is inserted before the selective accept, not before
4582    --    the accept statement (which is not part of a list anyway, and so would
4583    --    not accommodate inserted declarations)
4584
4585    --    We only need one address variable for the entire selective accept. So
4586    --    the Ann declaration is created only for the first accept alternative,
4587    --    and subsequent accept alternatives reference the same Ann variable.
4588
4589    --  We can distinguish the two cases by seeing whether the accept statement
4590    --  is part of a list. If not, then it must be in an accept alternative.
4591
4592    --  To expand the requeue statement, a label is provided at the end of the
4593    --  accept statement or alternative of which it is a part, so that the
4594    --  statement can be skipped after the requeue is complete. This label is
4595    --  created here rather than during the expansion of the accept statement,
4596    --  because it will be needed by any requeue statements within the accept,
4597    --  which are expanded before the accept.
4598
4599    procedure Expand_Accept_Declarations (N : Node_Id; Ent : Entity_Id) is
4600       Loc    : constant Source_Ptr := Sloc (N);
4601       Stats  : constant Node_Id    := Handled_Statement_Sequence (N);
4602       Ann    : Entity_Id           := Empty;
4603       Adecl  : Node_Id;
4604       Lab_Id : Node_Id;
4605       Lab    : Node_Id;
4606       Ldecl  : Node_Id;
4607       Ldecl2 : Node_Id;
4608
4609    begin
4610       if Expander_Active then
4611
4612          --  If we have no handled statement sequence, we may need to build
4613          --  a dummy sequence consisting of a null statement. This can be
4614          --  skipped if the trivial accept optimization is permitted.
4615
4616          if not Trivial_Accept_OK
4617            and then
4618              (No (Stats) or else Null_Statements (Statements (Stats)))
4619          then
4620             Set_Handled_Statement_Sequence (N,
4621               Make_Handled_Sequence_Of_Statements (Loc,
4622                 New_List (Make_Null_Statement (Loc))));
4623          end if;
4624
4625          --  Create and declare two labels to be placed at the end of the
4626          --  accept statement. The first label is used to allow requeues to
4627          --  skip the remainder of entry processing. The second label is used
4628          --  to skip the remainder of entry processing if the rendezvous
4629          --  completes in the middle of the accept body.
4630
4631          if Present (Handled_Statement_Sequence (N)) then
4632             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
4633             Set_Entity (Lab_Id,
4634               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
4635             Lab := Make_Label (Loc, Lab_Id);
4636             Ldecl :=
4637               Make_Implicit_Label_Declaration (Loc,
4638                 Defining_Identifier  => Entity (Lab_Id),
4639                 Label_Construct      => Lab);
4640             Append (Lab, Statements (Handled_Statement_Sequence (N)));
4641
4642             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
4643             Set_Entity (Lab_Id,
4644               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
4645             Lab := Make_Label (Loc, Lab_Id);
4646             Ldecl2 :=
4647               Make_Implicit_Label_Declaration (Loc,
4648                 Defining_Identifier  => Entity (Lab_Id),
4649                 Label_Construct      => Lab);
4650             Append (Lab, Statements (Handled_Statement_Sequence (N)));
4651
4652          else
4653             Ldecl := Empty;
4654             Ldecl2 := Empty;
4655          end if;
4656
4657          --  Case of stand alone accept statement
4658
4659          if Is_List_Member (N) then
4660
4661             if Present (Handled_Statement_Sequence (N)) then
4662                Ann :=
4663                  Make_Defining_Identifier (Loc,
4664                    Chars => New_Internal_Name ('A'));
4665
4666                Adecl :=
4667                  Make_Object_Declaration (Loc,
4668                    Defining_Identifier => Ann,
4669                    Object_Definition =>
4670                      New_Reference_To (RTE (RE_Address), Loc));
4671
4672                Insert_Before (N, Adecl);
4673                Analyze (Adecl);
4674
4675                Insert_Before (N, Ldecl);
4676                Analyze (Ldecl);
4677
4678                Insert_Before (N, Ldecl2);
4679                Analyze (Ldecl2);
4680             end if;
4681
4682          --  Case of accept statement which is in an accept alternative
4683
4684          else
4685             declare
4686                Acc_Alt : constant Node_Id := Parent (N);
4687                Sel_Acc : constant Node_Id := Parent (Acc_Alt);
4688                Alt     : Node_Id;
4689
4690             begin
4691                pragma Assert (Nkind (Acc_Alt) = N_Accept_Alternative);
4692                pragma Assert (Nkind (Sel_Acc) = N_Selective_Accept);
4693
4694                --  ??? Consider a single label for select statements
4695
4696                if Present (Handled_Statement_Sequence (N)) then
4697                   Prepend (Ldecl2,
4698                      Statements (Handled_Statement_Sequence (N)));
4699                   Analyze (Ldecl2);
4700
4701                   Prepend (Ldecl,
4702                      Statements (Handled_Statement_Sequence (N)));
4703                   Analyze (Ldecl);
4704                end if;
4705
4706                --  Find first accept alternative of the selective accept. A
4707                --  valid selective accept must have at least one accept in it.
4708
4709                Alt := First (Select_Alternatives (Sel_Acc));
4710
4711                while Nkind (Alt) /= N_Accept_Alternative loop
4712                   Next (Alt);
4713                end loop;
4714
4715                --  If we are the first accept statement, then we have to create
4716                --  the Ann variable, as for the stand alone case, except that
4717                --  it is inserted before the selective accept. Similarly, a
4718                --  label for requeue expansion must be declared.
4719
4720                if N = Accept_Statement (Alt) then
4721                   Ann :=
4722                     Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4723
4724                   Adecl :=
4725                     Make_Object_Declaration (Loc,
4726                       Defining_Identifier => Ann,
4727                       Object_Definition =>
4728                         New_Reference_To (RTE (RE_Address), Loc));
4729
4730                   Insert_Before (Sel_Acc, Adecl);
4731                   Analyze (Adecl);
4732
4733                --  If we are not the first accept statement, then find the Ann
4734                --  variable allocated by the first accept and use it.
4735
4736                else
4737                   Ann :=
4738                     Node (Last_Elmt (Accept_Address
4739                       (Entity (Entry_Direct_Name (Accept_Statement (Alt))))));
4740                end if;
4741             end;
4742          end if;
4743
4744          --  Merge here with Ann either created or referenced, and Adecl
4745          --  pointing to the corresponding declaration. Remaining processing
4746          --  is the same for the two cases.
4747
4748          if Present (Ann) then
4749             Append_Elmt (Ann, Accept_Address (Ent));
4750             Set_Debug_Info_Needed (Ann);
4751          end if;
4752
4753          --  Create renaming declarations for the entry formals. Each reference
4754          --  to a formal becomes a dereference of a component of the parameter
4755          --  block, whose address is held in Ann. These declarations are
4756          --  eventually inserted into the accept block, and analyzed there so
4757          --  that they have the proper scope for gdb and do not conflict with
4758          --  other declarations.
4759
4760          if Present (Parameter_Specifications (N))
4761            and then Present (Handled_Statement_Sequence (N))
4762          then
4763             declare
4764                Comp   : Entity_Id;
4765                Decl   : Node_Id;
4766                Formal : Entity_Id;
4767                New_F  : Entity_Id;
4768
4769             begin
4770                Push_Scope (Ent);
4771                Formal := First_Formal (Ent);
4772
4773                while Present (Formal) loop
4774                   Comp  := Entry_Component (Formal);
4775                   New_F :=
4776                     Make_Defining_Identifier (Loc, Chars (Formal));
4777
4778                   Set_Etype (New_F, Etype (Formal));
4779                   Set_Scope (New_F, Ent);
4780
4781                   --  Now we set debug info needed on New_F even though it does
4782                   --  not come from source, so that the debugger will get the
4783                   --  right information for these generated names.
4784
4785                   Set_Debug_Info_Needed (New_F);
4786
4787                   if Ekind (Formal) = E_In_Parameter then
4788                      Set_Ekind (New_F, E_Constant);
4789                   else
4790                      Set_Ekind (New_F, E_Variable);
4791                      Set_Extra_Constrained (New_F, Extra_Constrained (Formal));
4792                   end if;
4793
4794                   Set_Actual_Subtype (New_F, Actual_Subtype (Formal));
4795
4796                   Decl :=
4797                     Make_Object_Renaming_Declaration (Loc,
4798                       Defining_Identifier =>
4799                         New_F,
4800                       Subtype_Mark =>
4801                         New_Reference_To (Etype (Formal), Loc),
4802                       Name =>
4803                         Make_Explicit_Dereference (Loc,
4804                           Make_Selected_Component (Loc,
4805                             Prefix =>
4806                               Unchecked_Convert_To (
4807                                 Entry_Parameters_Type (Ent),
4808                                 New_Reference_To (Ann, Loc)),
4809                             Selector_Name =>
4810                               New_Reference_To (Comp, Loc))));
4811
4812                   if No (Declarations (N)) then
4813                      Set_Declarations (N, New_List);
4814                   end if;
4815
4816                   Append (Decl, Declarations (N));
4817                   Set_Renamed_Object (Formal, New_F);
4818                   Next_Formal (Formal);
4819                end loop;
4820
4821                End_Scope;
4822             end;
4823          end if;
4824       end if;
4825    end Expand_Accept_Declarations;
4826
4827    ---------------------------------------------
4828    -- Expand_Access_Protected_Subprogram_Type --
4829    ---------------------------------------------
4830
4831    procedure Expand_Access_Protected_Subprogram_Type (N : Node_Id) is
4832       Loc    : constant Source_Ptr := Sloc (N);
4833       Comps  : List_Id;
4834       T      : constant Entity_Id  := Defining_Identifier (N);
4835       D_T    : constant Entity_Id  := Designated_Type (T);
4836       D_T2   : constant Entity_Id  := Make_Defining_Identifier (Loc,
4837                                         Chars => New_Internal_Name ('D'));
4838       E_T    : constant Entity_Id  := Make_Defining_Identifier (Loc,
4839                                         Chars => New_Internal_Name ('E'));
4840       P_List : constant List_Id    := Build_Protected_Spec
4841                                         (N, RTE (RE_Address), D_T, False);
4842       Decl1  : Node_Id;
4843       Decl2  : Node_Id;
4844       Def1   : Node_Id;
4845
4846    begin
4847       --  Create access to subprogram with full signature
4848
4849       if Etype (D_T) /= Standard_Void_Type then
4850          Def1 :=
4851            Make_Access_Function_Definition (Loc,
4852              Parameter_Specifications => P_List,
4853              Result_Definition =>
4854                Copy_Result_Type (Result_Definition (Type_Definition (N))));
4855
4856       else
4857          Def1 :=
4858            Make_Access_Procedure_Definition (Loc,
4859              Parameter_Specifications => P_List);
4860       end if;
4861
4862       Decl1 :=
4863         Make_Full_Type_Declaration (Loc,
4864           Defining_Identifier => D_T2,
4865           Type_Definition => Def1);
4866
4867       Insert_After (N, Decl1);
4868       Analyze (Decl1);
4869
4870       --  Create Equivalent_Type, a record with two components for an access to
4871       --  object and an access to subprogram.
4872
4873       Comps := New_List (
4874         Make_Component_Declaration (Loc,
4875           Defining_Identifier =>
4876             Make_Defining_Identifier (Loc, New_Internal_Name ('P')),
4877           Component_Definition =>
4878             Make_Component_Definition (Loc,
4879               Aliased_Present => False,
4880               Subtype_Indication =>
4881                 New_Occurrence_Of (RTE (RE_Address), Loc))),
4882
4883         Make_Component_Declaration (Loc,
4884           Defining_Identifier =>
4885             Make_Defining_Identifier (Loc, New_Internal_Name ('S')),
4886           Component_Definition =>
4887             Make_Component_Definition (Loc,
4888               Aliased_Present => False,
4889               Subtype_Indication => New_Occurrence_Of (D_T2, Loc))));
4890
4891       Decl2 :=
4892         Make_Full_Type_Declaration (Loc,
4893           Defining_Identifier => E_T,
4894           Type_Definition =>
4895             Make_Record_Definition (Loc,
4896               Component_List =>
4897                 Make_Component_List (Loc,
4898                   Component_Items => Comps)));
4899
4900       Insert_After (Decl1, Decl2);
4901       Analyze (Decl2);
4902       Set_Equivalent_Type (T, E_T);
4903    end Expand_Access_Protected_Subprogram_Type;
4904
4905    --------------------------
4906    -- Expand_Entry_Barrier --
4907    --------------------------
4908
4909    procedure Expand_Entry_Barrier (N : Node_Id; Ent : Entity_Id) is
4910       Cond      : constant Node_Id   :=
4911                     Condition (Entry_Body_Formal_Part (N));
4912       Prot      : constant Entity_Id := Scope (Ent);
4913       Spec_Decl : constant Node_Id   := Parent (Prot);
4914       Func      : Node_Id;
4915       B_F       : Node_Id;
4916       Body_Decl : Node_Id;
4917
4918    begin
4919       if No_Run_Time_Mode then
4920          Error_Msg_CRT ("entry barrier", N);
4921          return;
4922       end if;
4923
4924       --  The body of the entry barrier must be analyzed in the context of the
4925       --  protected object, but its scope is external to it, just as any other
4926       --  unprotected version of a protected operation. The specification has
4927       --  been produced when the protected type declaration was elaborated. We
4928       --  build the body, insert it in the enclosing scope, but analyze it in
4929       --  the current context. A more uniform approach would be to treat the
4930       --  barrier just as a protected function, and discard the protected
4931       --  version of it because it is never called.
4932
4933       if Expander_Active then
4934          B_F := Build_Barrier_Function (N, Ent, Prot);
4935          Func := Barrier_Function (Ent);
4936          Set_Corresponding_Spec (B_F, Func);
4937
4938          Body_Decl := Parent (Corresponding_Body (Spec_Decl));
4939
4940          if Nkind (Parent (Body_Decl)) = N_Subunit then
4941             Body_Decl := Corresponding_Stub (Parent (Body_Decl));
4942          end if;
4943
4944          Insert_Before_And_Analyze (Body_Decl, B_F);
4945
4946          Set_Discriminals (Spec_Decl);
4947          Set_Scope (Func, Scope (Prot));
4948
4949       else
4950          Analyze_And_Resolve (Cond, Any_Boolean);
4951       end if;
4952
4953       --  The Ravenscar profile restricts barriers to simple variables declared
4954       --  within the protected object. We also allow Boolean constants, since
4955       --  these appear in several published examples and are also allowed by
4956       --  the Aonix compiler.
4957
4958       --  Note that after analysis variables in this context will be replaced
4959       --  by the corresponding prival, that is to say a renaming of a selected
4960       --  component of the form _Object.Var. If expansion is disabled, as
4961       --  within a generic, we check that the entity appears in the current
4962       --  scope.
4963
4964       if Is_Entity_Name (Cond) then
4965
4966          --  A small optimization of useless renamings. If the scope of the
4967          --  entity of the condition is not the barrier function, then the
4968          --  condition does not reference any of the generated renamings
4969          --  within the function.
4970
4971          if Expander_Active
4972            and then Scope (Entity (Cond)) /= Func
4973          then
4974             Set_Declarations (B_F, Empty_List);
4975          end if;
4976
4977          if Entity (Cond) = Standard_False
4978               or else
4979             Entity (Cond) = Standard_True
4980          then
4981             return;
4982
4983          elsif not Expander_Active
4984            and then Scope (Entity (Cond)) = Current_Scope
4985          then
4986             return;
4987
4988          --  Check for case of _object.all.field (note that the explicit
4989          --  dereference gets inserted by analyze/expand of _object.field)
4990
4991          elsif Present (Renamed_Object (Entity (Cond)))
4992            and then
4993              Nkind (Renamed_Object (Entity (Cond))) = N_Selected_Component
4994            and then
4995              Chars
4996                (Prefix
4997                  (Prefix (Renamed_Object (Entity (Cond))))) = Name_uObject
4998          then
4999             return;
5000          end if;
5001       end if;
5002
5003       --  It is not a boolean variable or literal, so check the restriction
5004
5005       Check_Restriction (Simple_Barriers, Cond);
5006    end Expand_Entry_Barrier;
5007
5008    ------------------------------
5009    -- Expand_N_Abort_Statement --
5010    ------------------------------
5011
5012    --  Expand abort T1, T2, .. Tn; into:
5013    --    Abort_Tasks (Task_List'(1 => T1.Task_Id, 2 => T2.Task_Id ...))
5014
5015    procedure Expand_N_Abort_Statement (N : Node_Id) is
5016       Loc    : constant Source_Ptr := Sloc (N);
5017       Tlist  : constant List_Id    := Names (N);
5018       Count  : Nat;
5019       Aggr   : Node_Id;
5020       Tasknm : Node_Id;
5021
5022    begin
5023       Aggr := Make_Aggregate (Loc, Component_Associations => New_List);
5024       Count := 0;
5025
5026       Tasknm := First (Tlist);
5027
5028       while Present (Tasknm) loop
5029          Count := Count + 1;
5030
5031          --  A task interface class-wide type object is being aborted.
5032          --  Retrieve its _task_id by calling a dispatching routine.
5033
5034          if Ada_Version >= Ada_05
5035            and then Ekind (Etype (Tasknm)) = E_Class_Wide_Type
5036            and then Is_Interface (Etype (Tasknm))
5037            and then Is_Task_Interface (Etype (Tasknm))
5038          then
5039             Append_To (Component_Associations (Aggr),
5040               Make_Component_Association (Loc,
5041                 Choices => New_List (
5042                   Make_Integer_Literal (Loc, Count)),
5043                 Expression =>
5044
5045                   --  Task_Id (Tasknm._disp_get_task_id)
5046
5047                   Make_Unchecked_Type_Conversion (Loc,
5048                     Subtype_Mark =>
5049                       New_Reference_To (RTE (RO_ST_Task_Id), Loc),
5050                     Expression =>
5051                       Make_Selected_Component (Loc,
5052                         Prefix =>
5053                           New_Copy_Tree (Tasknm),
5054                         Selector_Name =>
5055                           Make_Identifier (Loc, Name_uDisp_Get_Task_Id)))));
5056
5057          else
5058             Append_To (Component_Associations (Aggr),
5059               Make_Component_Association (Loc,
5060                 Choices => New_List (
5061                   Make_Integer_Literal (Loc, Count)),
5062                 Expression => Concurrent_Ref (Tasknm)));
5063          end if;
5064
5065          Next (Tasknm);
5066       end loop;
5067
5068       Rewrite (N,
5069         Make_Procedure_Call_Statement (Loc,
5070           Name => New_Reference_To (RTE (RE_Abort_Tasks), Loc),
5071           Parameter_Associations => New_List (
5072             Make_Qualified_Expression (Loc,
5073               Subtype_Mark => New_Reference_To (RTE (RE_Task_List), Loc),
5074               Expression => Aggr))));
5075
5076       Analyze (N);
5077    end Expand_N_Abort_Statement;
5078
5079    -------------------------------
5080    -- Expand_N_Accept_Statement --
5081    -------------------------------
5082
5083    --  This procedure handles expansion of accept statements that stand
5084    --  alone, i.e. they are not part of an accept alternative. The expansion
5085    --  of accept statement in accept alternatives is handled by the routines
5086    --  Expand_N_Accept_Alternative and Expand_N_Selective_Accept. The
5087    --  following description applies only to stand alone accept statements.
5088
5089    --  If there is no handled statement sequence, or only null statements,
5090    --  then this is called a trivial accept, and the expansion is:
5091
5092    --    Accept_Trivial (entry-index)
5093
5094    --  If there is a handled statement sequence, then the expansion is:
5095
5096    --    Ann : Address;
5097    --    {Lnn : Label}
5098
5099    --    begin
5100    --       begin
5101    --          Accept_Call (entry-index, Ann);
5102    --          Renaming_Declarations for formals
5103    --          <statement sequence from N_Accept_Statement node>
5104    --          Complete_Rendezvous;
5105    --          <<Lnn>>
5106    --
5107    --       exception
5108    --          when ... =>
5109    --             <exception handler from N_Accept_Statement node>
5110    --             Complete_Rendezvous;
5111    --          when ... =>
5112    --             <exception handler from N_Accept_Statement node>
5113    --             Complete_Rendezvous;
5114    --          ...
5115    --       end;
5116
5117    --    exception
5118    --       when all others =>
5119    --          Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
5120    --    end;
5121
5122    --  The first three declarations were already inserted ahead of the accept
5123    --  statement by the Expand_Accept_Declarations procedure, which was called
5124    --  directly from the semantics during analysis of the accept statement,
5125    --  before analyzing its contained statements.
5126
5127    --  The declarations from the N_Accept_Statement, as noted in Sinfo, come
5128    --  from possible expansion activity (the original source of course does
5129    --  not have any declarations associated with the accept statement, since
5130    --  an accept statement has no declarative part). In particular, if the
5131    --  expander is active, the first such declaration is the declaration of
5132    --  the Accept_Params_Ptr entity (see Sem_Ch9.Analyze_Accept_Statement).
5133    --
5134    --  The two blocks are merged into a single block if the inner block has
5135    --  no exception handlers, but otherwise two blocks are required, since
5136    --  exceptions might be raised in the exception handlers of the inner
5137    --  block, and Exceptional_Complete_Rendezvous must be called.
5138
5139    procedure Expand_N_Accept_Statement (N : Node_Id) is
5140       Loc     : constant Source_Ptr := Sloc (N);
5141       Stats   : constant Node_Id    := Handled_Statement_Sequence (N);
5142       Ename   : constant Node_Id    := Entry_Direct_Name (N);
5143       Eindx   : constant Node_Id    := Entry_Index (N);
5144       Eent    : constant Entity_Id  := Entity (Ename);
5145       Acstack : constant Elist_Id   := Accept_Address (Eent);
5146       Ann     : constant Entity_Id  := Node (Last_Elmt (Acstack));
5147       Ttyp    : constant Entity_Id  := Etype (Scope (Eent));
5148       Blkent  : Entity_Id;
5149       Call    : Node_Id;
5150       Block   : Node_Id;
5151
5152    --  Start of processing for Expand_N_Accept_Statement
5153
5154    begin
5155       --  If accept statement is not part of a list, then its parent must be
5156       --  an accept alternative, and, as described above, we do not do any
5157       --  expansion for such accept statements at this level.
5158
5159       if not Is_List_Member (N) then
5160          pragma Assert (Nkind (Parent (N)) = N_Accept_Alternative);
5161          return;
5162
5163       --  Trivial accept case (no statement sequence, or null statements).
5164       --  If the accept statement has declarations, then just insert them
5165       --  before the procedure call.
5166
5167       elsif Trivial_Accept_OK
5168         and then (No (Stats) or else Null_Statements (Statements (Stats)))
5169       then
5170          --  Remove declarations for renamings, because the parameter block
5171          --  will not be assigned.
5172
5173          declare
5174             D      : Node_Id;
5175             Next_D : Node_Id;
5176
5177          begin
5178             D := First (Declarations (N));
5179
5180             while Present (D) loop
5181                Next_D := Next (D);
5182                if Nkind (D) = N_Object_Renaming_Declaration then
5183                   Remove (D);
5184                end if;
5185
5186                D := Next_D;
5187             end loop;
5188          end;
5189
5190          if Present (Declarations (N)) then
5191             Insert_Actions (N, Declarations (N));
5192          end if;
5193
5194          Rewrite (N,
5195            Make_Procedure_Call_Statement (Loc,
5196              Name => New_Reference_To (RTE (RE_Accept_Trivial), Loc),
5197              Parameter_Associations => New_List (
5198                Entry_Index_Expression (Loc, Entity (Ename), Eindx, Ttyp))));
5199
5200          Analyze (N);
5201
5202          --  Discard Entry_Address that was created for it, so it will not be
5203          --  emitted if this accept statement is in the statement part of a
5204          --  delay alternative.
5205
5206          if Present (Stats) then
5207             Remove_Last_Elmt (Acstack);
5208          end if;
5209
5210       --  Case of statement sequence present
5211
5212       else
5213          --  Construct the block, using the declarations from the accept
5214          --  statement if any to initialize the declarations of the block.
5215
5216          Blkent := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5217          Set_Ekind (Blkent, E_Block);
5218          Set_Etype (Blkent, Standard_Void_Type);
5219          Set_Scope (Blkent, Current_Scope);
5220
5221          Block :=
5222            Make_Block_Statement (Loc,
5223              Identifier                 => New_Reference_To (Blkent, Loc),
5224              Declarations               => Declarations (N),
5225              Handled_Statement_Sequence => Build_Accept_Body (N));
5226
5227          --  Prepend call to Accept_Call to main statement sequence If the
5228          --  accept has exception handlers, the statement sequence is wrapped
5229          --  in a block. Insert call and renaming declarations in the
5230          --  declarations of the block, so they are elaborated before the
5231          --  handlers.
5232
5233          Call :=
5234            Make_Procedure_Call_Statement (Loc,
5235              Name => New_Reference_To (RTE (RE_Accept_Call), Loc),
5236              Parameter_Associations => New_List (
5237                Entry_Index_Expression (Loc, Entity (Ename), Eindx, Ttyp),
5238                New_Reference_To (Ann, Loc)));
5239
5240          if Parent (Stats) = N then
5241             Prepend (Call, Statements (Stats));
5242          else
5243             Set_Declarations
5244               (Parent (Stats),
5245                 New_List (Call));
5246          end if;
5247
5248          Analyze (Call);
5249
5250          Push_Scope (Blkent);
5251
5252          declare
5253             D      : Node_Id;
5254             Next_D : Node_Id;
5255             Typ    : Entity_Id;
5256
5257          begin
5258             D := First (Declarations (N));
5259             while Present (D) loop
5260                Next_D := Next (D);
5261
5262                if Nkind (D) = N_Object_Renaming_Declaration then
5263
5264                   --  The renaming declarations for the formals were created
5265                   --  during analysis of the accept statement, and attached to
5266                   --  the list of declarations. Place them now in the context
5267                   --  of the accept block or subprogram.
5268
5269                   Remove (D);
5270                   Typ := Entity (Subtype_Mark (D));
5271                   Insert_After (Call, D);
5272                   Analyze (D);
5273
5274                   --  If the formal is class_wide, it does not have an actual
5275                   --  subtype. The analysis of the renaming declaration creates
5276                   --  one, but we need to retain the class-wide nature of the
5277                   --  entity.
5278
5279                   if Is_Class_Wide_Type (Typ) then
5280                      Set_Etype (Defining_Identifier (D), Typ);
5281                   end if;
5282
5283                end if;
5284
5285                D := Next_D;
5286             end loop;
5287          end;
5288
5289          End_Scope;
5290
5291          --  Replace the accept statement by the new block
5292
5293          Rewrite (N, Block);
5294          Analyze (N);
5295
5296          --  Last step is to unstack the Accept_Address value
5297
5298          Remove_Last_Elmt (Acstack);
5299       end if;
5300    end Expand_N_Accept_Statement;
5301
5302    ----------------------------------
5303    -- Expand_N_Asynchronous_Select --
5304    ----------------------------------
5305
5306    --  This procedure assumes that the trigger statement is an entry call or
5307    --  a dispatching procedure call. A delay alternative should already have
5308    --  been expanded into an entry call to the appropriate delay object Wait
5309    --  entry.
5310
5311    --  If the trigger is a task entry call, the select is implemented with
5312    --  a Task_Entry_Call:
5313
5314    --    declare
5315    --       B : Boolean;
5316    --       C : Boolean;
5317    --       P : parms := (parm, parm, parm);
5318
5319    --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
5320
5321    --       procedure _clean is
5322    --       begin
5323    --          ...
5324    --          Cancel_Task_Entry_Call (C);
5325    --          ...
5326    --       end _clean;
5327
5328    --    begin
5329    --       Abort_Defer;
5330    --       Task_Entry_Call
5331    --         (<acceptor-task>,    --  Acceptor
5332    --          <entry-index>,      --  E
5333    --          P'Address,          --  Uninterpreted_Data
5334    --          Asynchronous_Call,  --  Mode
5335    --          B);                 --  Rendezvous_Successful
5336
5337    --       begin
5338    --          begin
5339    --             Abort_Undefer;
5340    --             <abortable-part>
5341    --          at end
5342    --             _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5343    --          end;
5344    --       exception
5345    --          when Abort_Signal => Abort_Undefer;
5346    --       end;
5347
5348    --       parm := P.param;
5349    --       parm := P.param;
5350    --       ...
5351    --       if not C then
5352    --          <triggered-statements>
5353    --       end if;
5354    --    end;
5355
5356    --  Note that Build_Simple_Entry_Call is used to expand the entry of the
5357    --  asynchronous entry call (by Expand_N_Entry_Call_Statement procedure)
5358    --  as follows:
5359
5360    --    declare
5361    --       P : parms := (parm, parm, parm);
5362    --    begin
5363    --       Call_Simple (acceptor-task, entry-index, P'Address);
5364    --       parm := P.param;
5365    --       parm := P.param;
5366    --       ...
5367    --    end;
5368
5369    --  so the task at hand is to convert the latter expansion into the former
5370
5371    --  If the trigger is a protected entry call, the select is implemented
5372    --  with Protected_Entry_Call:
5373
5374    --  declare
5375    --     P   : E1_Params := (param, param, param);
5376    --     Bnn : Communications_Block;
5377
5378    --  begin
5379    --     declare
5380
5381    --        --  Clean is added by Exp_Ch7.Expand_Cleanup_Actions
5382
5383    --        procedure _clean is
5384    --        begin
5385    --           ...
5386    --           if Enqueued (Bnn) then
5387    --              Cancel_Protected_Entry_Call (Bnn);
5388    --           end if;
5389    --           ...
5390    --        end _clean;
5391
5392    --     begin
5393    --        begin
5394    --           Protected_Entry_Call
5395    --             (po._object'Access,  --  Object
5396    --              <entry index>,      --  E
5397    --              P'Address,          --  Uninterpreted_Data
5398    --              Asynchronous_Call,  --  Mode
5399    --              Bnn);               --  Block
5400
5401    --           if Enqueued (Bnn) then
5402    --              <abortable-part>
5403    --           end if;
5404    --        at end
5405    --           _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5406    --        end;
5407    --     exception
5408    --        when Abort_Signal => Abort_Undefer;
5409    --     end;
5410
5411    --     if not Cancelled (Bnn) then
5412    --        <triggered-statements>
5413    --     end if;
5414    --  end;
5415
5416    --  Build_Simple_Entry_Call is used to expand the all to a simple protected
5417    --  entry call:
5418
5419    --  declare
5420    --     P   : E1_Params := (param, param, param);
5421    --     Bnn : Communications_Block;
5422
5423    --  begin
5424    --     Protected_Entry_Call
5425    --       (po._object'Access,  --  Object
5426    --        <entry index>,      --  E
5427    --        P'Address,          --  Uninterpreted_Data
5428    --        Simple_Call,        --  Mode
5429    --        Bnn);               --  Block
5430    --     parm := P.param;
5431    --     parm := P.param;
5432    --       ...
5433    --  end;
5434
5435    --  Ada 2005 (AI-345): If the trigger is a dispatching call, the select is
5436    --  expanded into:
5437
5438    --    declare
5439    --       B   : Boolean := False;
5440    --       Bnn : Communication_Block;
5441    --       C   : Ada.Tags.Prim_Op_Kind;
5442    --       D   : System.Storage_Elements.Dummy_Communication_Block;
5443    --       K   : Ada.Tags.Tagged_Kind :=
5444    --               Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
5445    --       P   : Parameters := (Param1 .. ParamN);
5446    --       S   : Integer;
5447    --       U   : Boolean;
5448
5449    --    begin
5450    --       if K = Ada.Tags.TK_Limited_Tagged then
5451    --          <dispatching-call>;
5452    --          <triggering-statements>;
5453
5454    --       else
5455    --          S :=
5456    --            Ada.Tags.Get_Offset_Index
5457    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
5458
5459    --          _Disp_Get_Prim_Op_Kind (<object>, S, C);
5460
5461    --          if C = POK_Protected_Entry then
5462    --             declare
5463    --                procedure _clean is
5464    --                begin
5465    --                   if Enqueued (Bnn) then
5466    --                      Cancel_Protected_Entry_Call (Bnn);
5467    --                   end if;
5468    --                end _clean;
5469
5470    --             begin
5471    --                begin
5472    --                   _Disp_Asynchronous_Select
5473    --                     (<object>, S, P'Address, D, B);
5474    --                   Bnn := Communication_Block (D);
5475
5476    --                   Param1 := P.Param1;
5477    --                   ...
5478    --                   ParamN := P.ParamN;
5479
5480    --                   if Enqueued (Bnn) then
5481    --                      <abortable-statements>
5482    --                   end if;
5483    --                at end
5484    --                   _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5485    --                end;
5486    --             exception
5487    --                when Abort_Signal => Abort_Undefer;
5488    --             end;
5489
5490    --             if not Cancelled (Bnn) then
5491    --                <triggering-statements>
5492    --             end if;
5493
5494    --          elsif C = POK_Task_Entry then
5495    --             declare
5496    --                procedure _clean is
5497    --                begin
5498    --                   Cancel_Task_Entry_Call (U);
5499    --                end _clean;
5500
5501    --             begin
5502    --                Abort_Defer;
5503
5504    --                _Disp_Asynchronous_Select
5505    --                  (<object>, S, P'Address, D, B);
5506    --                Bnn := Communication_Bloc (D);
5507
5508    --                Param1 := P.Param1;
5509    --                ...
5510    --                ParamN := P.ParamN;
5511
5512    --                begin
5513    --                   begin
5514    --                      Abort_Undefer;
5515    --                      <abortable-statements>
5516    --                   at end
5517    --                      _clean;  --  Added by Exp_Ch7.Expand_Cleanup_Actions
5518    --                   end;
5519    --                exception
5520    --                   when Abort_Signal => Abort_Undefer;
5521    --                end;
5522
5523    --                if not U then
5524    --                   <triggering-statements>
5525    --                end if;
5526    --             end;
5527
5528    --          else
5529    --             <dispatching-call>;
5530    --             <triggering-statements>
5531    --          end if;
5532    --       end if;
5533    --    end;
5534
5535    --  The job is to convert this to the asynchronous form
5536
5537    --  If the trigger is a delay statement, it will have been expanded into a
5538    --  call to one of the GNARL delay procedures. This routine will convert
5539    --  this into a protected entry call on a delay object and then continue
5540    --  processing as for a protected entry call trigger. This requires
5541    --  declaring a Delay_Block object and adding a pointer to this object to
5542    --  the parameter list of the delay procedure to form the parameter list of
5543    --  the entry call. This object is used by the runtime to queue the delay
5544    --  request.
5545
5546    --  For a description of the use of P and the assignments after the call,
5547    --  see Expand_N_Entry_Call_Statement.
5548
5549    procedure Expand_N_Asynchronous_Select (N : Node_Id) is
5550       Loc    : constant Source_Ptr := Sloc (N);
5551       Abrt   : constant Node_Id    := Abortable_Part (N);
5552       Astats : constant List_Id    := Statements (Abrt);
5553       Trig   : constant Node_Id    := Triggering_Alternative (N);
5554       Tstats : constant List_Id    := Statements (Trig);
5555
5556       Abort_Block_Ent   : Entity_Id;
5557       Abortable_Block   : Node_Id;
5558       Actuals           : List_Id;
5559       Blk_Ent           : Entity_Id;
5560       Blk_Typ           : Entity_Id;
5561       Call              : Node_Id;
5562       Call_Ent          : Entity_Id;
5563       Cancel_Param      : Entity_Id;
5564       Cleanup_Block     : Node_Id;
5565       Cleanup_Block_Ent : Entity_Id;
5566       Cleanup_Stmts     : List_Id;
5567       Conc_Typ_Stmts    : List_Id;
5568       Concval           : Node_Id;
5569       Dblock_Ent        : Entity_Id;
5570       Decl              : Node_Id;
5571       Decls             : List_Id;
5572       Ecall             : Node_Id;
5573       Ename             : Node_Id;
5574       Enqueue_Call      : Node_Id;
5575       Formals           : List_Id;
5576       Hdle              : List_Id;
5577       Index             : Node_Id;
5578       Lim_Typ_Stmts     : List_Id;
5579       N_Orig            : Node_Id;
5580       Obj               : Entity_Id;
5581       Param             : Node_Id;
5582       Params            : List_Id;
5583       Pdef              : Entity_Id;
5584       ProtE_Stmts       : List_Id;
5585       ProtP_Stmts       : List_Id;
5586       Stmt              : Node_Id;
5587       Stmts             : List_Id;
5588       Target_Undefer    : RE_Id;
5589       TaskE_Stmts       : List_Id;
5590       Undefer_Args      : List_Id := No_List;
5591
5592       B   : Entity_Id;  --  Call status flag
5593       Bnn : Entity_Id;  --  Communication block
5594       C   : Entity_Id;  --  Call kind
5595       K   : Entity_Id;  --  Tagged kind
5596       P   : Entity_Id;  --  Parameter block
5597       S   : Entity_Id;  --  Primitive operation slot
5598       T   : Entity_Id;  --  Additional status flag
5599
5600    begin
5601       Blk_Ent := Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5602       Ecall   := Triggering_Statement (Trig);
5603
5604       --  The arguments in the call may require dynamic allocation, and the
5605       --  call statement may have been transformed into a block. The block
5606       --  may contain additional declarations for internal entities, and the
5607       --  original call is found by sequential search.
5608
5609       if Nkind (Ecall) = N_Block_Statement then
5610          Ecall := First (Statements (Handled_Statement_Sequence (Ecall)));
5611          while not Nkind_In (Ecall, N_Procedure_Call_Statement,
5612                                     N_Entry_Call_Statement)
5613          loop
5614             Next (Ecall);
5615          end loop;
5616       end if;
5617
5618       --  This is either a dispatching call or a delay statement used as a
5619       --  trigger which was expanded into a procedure call.
5620
5621       if Nkind (Ecall) = N_Procedure_Call_Statement then
5622          if Ada_Version >= Ada_05
5623            and then
5624              (No (Original_Node (Ecall))
5625                 or else not Nkind_In (Original_Node (Ecall),
5626                                         N_Delay_Relative_Statement,
5627                                         N_Delay_Until_Statement))
5628          then
5629             Extract_Dispatching_Call (Ecall, Call_Ent, Obj, Actuals, Formals);
5630
5631             Decls := New_List;
5632             Stmts := New_List;
5633
5634             --  Call status flag processing, generate:
5635             --    B : Boolean := False;
5636
5637             B := Build_B (Loc, Decls);
5638
5639             --  Communication block processing, generate:
5640             --    Bnn : Communication_Block;
5641
5642             Bnn := Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
5643
5644             Append_To (Decls,
5645               Make_Object_Declaration (Loc,
5646                 Defining_Identifier =>
5647                   Bnn,
5648                 Object_Definition =>
5649                   New_Reference_To (RTE (RE_Communication_Block), Loc)));
5650
5651             --  Call kind processing, generate:
5652             --    C : Ada.Tags.Prim_Op_Kind;
5653
5654             C := Build_C (Loc, Decls);
5655
5656             --  Tagged kind processing, generate:
5657             --    K : Ada.Tags.Tagged_Kind :=
5658             --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
5659
5660             --  Dummy communication block, generate:
5661             --    D : Dummy_Communication_Block;
5662
5663             Append_To (Decls,
5664               Make_Object_Declaration (Loc,
5665                 Defining_Identifier =>
5666                   Make_Defining_Identifier (Loc, Name_uD),
5667                 Object_Definition =>
5668                   New_Reference_To (
5669                     RTE (RE_Dummy_Communication_Block), Loc)));
5670
5671             K := Build_K (Loc, Decls, Obj);
5672
5673             --  Parameter block processing
5674
5675             Blk_Typ := Build_Parameter_Block
5676                          (Loc, Actuals, Formals, Decls);
5677             P       := Parameter_Block_Pack
5678                          (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
5679
5680             --  Dispatch table slot processing, generate:
5681             --    S : Integer;
5682
5683             S := Build_S (Loc, Decls);
5684
5685             --  Additional status flag processing, generate:
5686
5687             T := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
5688
5689             Append_To (Decls,
5690               Make_Object_Declaration (Loc,
5691                 Defining_Identifier =>
5692                   T,
5693                 Object_Definition =>
5694                   New_Reference_To (Standard_Boolean, Loc)));
5695
5696             ------------------------------
5697             -- Protected entry handling --
5698             ------------------------------
5699
5700             --  Generate:
5701             --    Param1 := P.Param1;
5702             --    ...
5703             --    ParamN := P.ParamN;
5704
5705             Cleanup_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
5706
5707             --  Generate:
5708             --    Bnn := Communication_Block (D);
5709
5710             Prepend_To (Cleanup_Stmts,
5711               Make_Assignment_Statement (Loc,
5712                 Name =>
5713                   New_Reference_To (Bnn, Loc),
5714                 Expression =>
5715                   Make_Unchecked_Type_Conversion (Loc,
5716                     Subtype_Mark =>
5717                       New_Reference_To (RTE (RE_Communication_Block), Loc),
5718                     Expression =>
5719                       Make_Identifier (Loc, Name_uD))));
5720
5721             --  Generate:
5722             --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
5723
5724             Prepend_To (Cleanup_Stmts,
5725               Make_Procedure_Call_Statement (Loc,
5726                 Name =>
5727                   New_Reference_To (
5728                     Find_Prim_Op (Etype (Etype (Obj)),
5729                       Name_uDisp_Asynchronous_Select),
5730                     Loc),
5731                 Parameter_Associations =>
5732                   New_List (
5733                     New_Copy_Tree (Obj),             --  <object>
5734                     New_Reference_To (S, Loc),       --  S
5735                     Make_Attribute_Reference (Loc,   --  P'Address
5736                       Prefix =>
5737                         New_Reference_To (P, Loc),
5738                       Attribute_Name =>
5739                         Name_Address),
5740                     Make_Identifier (Loc, Name_uD),  --  D
5741                     New_Reference_To (B, Loc))));    --  B
5742
5743             --  Generate:
5744             --    if Enqueued (Bnn) then
5745             --       <abortable-statements>
5746             --    end if;
5747
5748             Append_To (Cleanup_Stmts,
5749               Make_If_Statement (Loc,
5750                 Condition =>
5751                   Make_Function_Call (Loc,
5752                     Name =>
5753                       New_Reference_To (RTE (RE_Enqueued), Loc),
5754                     Parameter_Associations =>
5755                       New_List (
5756                         New_Reference_To (Bnn, Loc))),
5757
5758                 Then_Statements =>
5759                   New_Copy_List_Tree (Astats)));
5760
5761             --  Wrap the statements in a block. Exp_Ch7.Expand_Cleanup_Actions
5762             --  will then generate a _clean for the communication block Bnn.
5763
5764             --  Generate:
5765             --    declare
5766             --       procedure _clean is
5767             --       begin
5768             --          if Enqueued (Bnn) then
5769             --             Cancel_Protected_Entry_Call (Bnn);
5770             --          end if;
5771             --       end _clean;
5772             --    begin
5773             --       Cleanup_Stmts
5774             --    at end
5775             --       _clean;
5776             --    end;
5777
5778             Cleanup_Block_Ent :=
5779               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
5780
5781             Cleanup_Block :=
5782               Build_Cleanup_Block (Loc, Cleanup_Block_Ent, Cleanup_Stmts, Bnn);
5783
5784             --  Wrap the cleanup block in an exception handling block
5785
5786             --  Generate:
5787             --    begin
5788             --       Cleanup_Block
5789             --    exception
5790             --       when Abort_Signal => Abort_Undefer;
5791             --    end;
5792
5793             Abort_Block_Ent :=
5794               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5795
5796             ProtE_Stmts :=
5797               New_List (
5798                 Make_Implicit_Label_Declaration (Loc,
5799                   Defining_Identifier =>
5800                     Abort_Block_Ent),
5801
5802                 Build_Abort_Block
5803                   (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
5804
5805             --  Generate:
5806             --    if not Cancelled (Bnn) then
5807             --       <triggering-statements>
5808             --    end if;
5809
5810             Append_To (ProtE_Stmts,
5811               Make_If_Statement (Loc,
5812                 Condition =>
5813                   Make_Op_Not (Loc,
5814                     Right_Opnd =>
5815                       Make_Function_Call (Loc,
5816                         Name =>
5817                           New_Reference_To (RTE (RE_Cancelled), Loc),
5818                         Parameter_Associations =>
5819                           New_List (
5820                             New_Reference_To (Bnn, Loc)))),
5821
5822                 Then_Statements =>
5823                   New_Copy_List_Tree (Tstats)));
5824
5825             -------------------------
5826             -- Task entry handling --
5827             -------------------------
5828
5829             --  Generate:
5830             --    Param1 := P.Param1;
5831             --    ...
5832             --    ParamN := P.ParamN;
5833
5834             TaskE_Stmts := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
5835
5836             --  Generate:
5837             --    Bnn := Communication_Block (D);
5838
5839             Append_To (TaskE_Stmts,
5840               Make_Assignment_Statement (Loc,
5841                 Name =>
5842                   New_Reference_To (Bnn, Loc),
5843                 Expression =>
5844                   Make_Unchecked_Type_Conversion (Loc,
5845                     Subtype_Mark =>
5846                       New_Reference_To (RTE (RE_Communication_Block), Loc),
5847                     Expression =>
5848                       Make_Identifier (Loc, Name_uD))));
5849
5850             --  Generate:
5851             --    _Disp_Asynchronous_Select (<object>, S, P'Address, D, B);
5852
5853             Prepend_To (TaskE_Stmts,
5854               Make_Procedure_Call_Statement (Loc,
5855                 Name =>
5856                   New_Reference_To (
5857                     Find_Prim_Op (Etype (Etype (Obj)),
5858                       Name_uDisp_Asynchronous_Select),
5859                     Loc),
5860                 Parameter_Associations =>
5861                   New_List (
5862                     New_Copy_Tree (Obj),             --  <object>
5863                     New_Reference_To (S, Loc),       --  S
5864                     Make_Attribute_Reference (Loc,   --  P'Address
5865                       Prefix =>
5866                         New_Reference_To (P, Loc),
5867                       Attribute_Name =>
5868                         Name_Address),
5869                     Make_Identifier (Loc, Name_uD),  --  D
5870                     New_Reference_To (B, Loc))));    --  B
5871
5872             --  Generate:
5873             --    Abort_Defer;
5874
5875             Prepend_To (TaskE_Stmts,
5876               Make_Procedure_Call_Statement (Loc,
5877                 Name =>
5878                   New_Reference_To (RTE (RE_Abort_Defer), Loc),
5879                 Parameter_Associations =>
5880                   No_List));
5881
5882             --  Generate:
5883             --    Abort_Undefer;
5884             --    <abortable-statements>
5885
5886             Cleanup_Stmts := New_Copy_List_Tree (Astats);
5887
5888             Prepend_To (Cleanup_Stmts,
5889               Make_Procedure_Call_Statement (Loc,
5890                 Name =>
5891                   New_Reference_To (RTE (RE_Abort_Undefer), Loc),
5892                 Parameter_Associations =>
5893                   No_List));
5894
5895             --  Wrap the statements in a block. Exp_Ch7.Expand_Cleanup_Actions
5896             --  will generate a _clean for the additional status flag.
5897
5898             --  Generate:
5899             --    declare
5900             --       procedure _clean is
5901             --       begin
5902             --          Cancel_Task_Entry_Call (U);
5903             --       end _clean;
5904             --    begin
5905             --       Cleanup_Stmts
5906             --    at end
5907             --       _clean;
5908             --    end;
5909
5910             Cleanup_Block_Ent :=
5911               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
5912
5913             Cleanup_Block :=
5914               Build_Cleanup_Block (Loc, Cleanup_Block_Ent, Cleanup_Stmts, T);
5915
5916             --  Wrap the cleanup block in an exception handling block
5917
5918             --  Generate:
5919             --    begin
5920             --       Cleanup_Block
5921             --    exception
5922             --       when Abort_Signal => Abort_Undefer;
5923             --    end;
5924
5925             Abort_Block_Ent :=
5926               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5927
5928             Append_To (TaskE_Stmts,
5929               Make_Implicit_Label_Declaration (Loc,
5930                 Defining_Identifier =>
5931                   Abort_Block_Ent));
5932
5933             Append_To (TaskE_Stmts,
5934               Build_Abort_Block
5935                 (Loc, Abort_Block_Ent, Cleanup_Block_Ent, Cleanup_Block));
5936
5937             --  Generate:
5938             --    if not T then
5939             --       <triggering-statements>
5940             --    end if;
5941
5942             Append_To (TaskE_Stmts,
5943               Make_If_Statement (Loc,
5944                 Condition =>
5945                   Make_Op_Not (Loc,
5946                     Right_Opnd =>
5947                       New_Reference_To (T, Loc)),
5948
5949                 Then_Statements =>
5950                   New_Copy_List_Tree (Tstats)));
5951
5952             ----------------------------------
5953             -- Protected procedure handling --
5954             ----------------------------------
5955
5956             --  Generate:
5957             --    <dispatching-call>;
5958             --    <triggering-statements>
5959
5960             ProtP_Stmts := New_Copy_List_Tree (Tstats);
5961             Prepend_To (ProtP_Stmts, New_Copy_Tree (Ecall));
5962
5963             --  Generate:
5964             --    S := Ada.Tags.Get_Offset_Index
5965             --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
5966
5967             Conc_Typ_Stmts :=
5968               New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
5969
5970             --  Generate:
5971             --    _Disp_Get_Prim_Op_Kind (<object>, S, C);
5972
5973             Append_To (Conc_Typ_Stmts,
5974               Make_Procedure_Call_Statement (Loc,
5975                 Name =>
5976                   New_Reference_To (
5977                     Find_Prim_Op (Etype (Etype (Obj)),
5978                       Name_uDisp_Get_Prim_Op_Kind),
5979                     Loc),
5980                 Parameter_Associations =>
5981                   New_List (
5982                     New_Copy_Tree (Obj),
5983                     New_Reference_To (S, Loc),
5984                     New_Reference_To (C, Loc))));
5985
5986             --  Generate:
5987             --    if C = POK_Procedure_Entry then
5988             --       ProtE_Stmts
5989             --    elsif C = POK_Task_Entry then
5990             --       TaskE_Stmts
5991             --    else
5992             --       ProtP_Stmts
5993             --    end if;
5994
5995             Append_To (Conc_Typ_Stmts,
5996               Make_If_Statement (Loc,
5997                 Condition =>
5998                   Make_Op_Eq (Loc,
5999                     Left_Opnd =>
6000                       New_Reference_To (C, Loc),
6001                     Right_Opnd =>
6002                       New_Reference_To (RTE (RE_POK_Protected_Entry), Loc)),
6003
6004                 Then_Statements =>
6005                   ProtE_Stmts,
6006
6007                 Elsif_Parts =>
6008                   New_List (
6009                     Make_Elsif_Part (Loc,
6010                       Condition =>
6011                         Make_Op_Eq (Loc,
6012                           Left_Opnd =>
6013                             New_Reference_To (C, Loc),
6014                           Right_Opnd =>
6015                             New_Reference_To (RTE (RE_POK_Task_Entry), Loc)),
6016
6017                       Then_Statements =>
6018                         TaskE_Stmts)),
6019
6020                 Else_Statements =>
6021                   ProtP_Stmts));
6022
6023             --  Generate:
6024             --    <dispatching-call>;
6025             --    <triggering-statements>
6026
6027             Lim_Typ_Stmts := New_Copy_List_Tree (Tstats);
6028             Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (Ecall));
6029
6030             --  Generate:
6031             --    if K = Ada.Tags.TK_Limited_Tagged then
6032             --       Lim_Typ_Stmts
6033             --    else
6034             --       Conc_Typ_Stmts
6035             --    end if;
6036
6037             Append_To (Stmts,
6038               Make_If_Statement (Loc,
6039                 Condition =>
6040                    Make_Op_Eq (Loc,
6041                      Left_Opnd =>
6042                        New_Reference_To (K, Loc),
6043                      Right_Opnd =>
6044                        New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
6045
6046                 Then_Statements =>
6047                   Lim_Typ_Stmts,
6048
6049                 Else_Statements =>
6050                   Conc_Typ_Stmts));
6051
6052             Rewrite (N,
6053               Make_Block_Statement (Loc,
6054                 Declarations =>
6055                   Decls,
6056                 Handled_Statement_Sequence =>
6057                   Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6058
6059             Analyze (N);
6060             return;
6061
6062          --  Delay triggering statement processing
6063
6064          else
6065             --  Add a Delay_Block object to the parameter list of the delay
6066             --  procedure to form the parameter list of the Wait entry call.
6067
6068             Dblock_Ent :=
6069               Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
6070
6071             Pdef := Entity (Name (Ecall));
6072
6073             if Is_RTE (Pdef, RO_CA_Delay_For) then
6074                Enqueue_Call :=
6075                  New_Reference_To (RTE (RE_Enqueue_Duration), Loc);
6076
6077             elsif Is_RTE (Pdef, RO_CA_Delay_Until) then
6078                Enqueue_Call :=
6079                  New_Reference_To (RTE (RE_Enqueue_Calendar), Loc);
6080
6081             else pragma Assert (Is_RTE (Pdef, RO_RT_Delay_Until));
6082                Enqueue_Call := New_Reference_To (RTE (RE_Enqueue_RT), Loc);
6083             end if;
6084
6085             Append_To (Parameter_Associations (Ecall),
6086               Make_Attribute_Reference (Loc,
6087                 Prefix => New_Reference_To (Dblock_Ent, Loc),
6088                 Attribute_Name => Name_Unchecked_Access));
6089
6090             --  Create the inner block to protect the abortable part
6091
6092             Hdle := New_List (
6093               Make_Implicit_Exception_Handler (Loc,
6094                 Exception_Choices =>
6095                   New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6096                 Statements => New_List (
6097                   Make_Procedure_Call_Statement (Loc,
6098                     Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
6099
6100             Prepend_To (Astats,
6101               Make_Procedure_Call_Statement (Loc,
6102                 Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)));
6103
6104             Abortable_Block :=
6105               Make_Block_Statement (Loc,
6106                 Identifier => New_Reference_To (Blk_Ent, Loc),
6107                 Handled_Statement_Sequence =>
6108                   Make_Handled_Sequence_Of_Statements (Loc,
6109                     Statements => Astats),
6110                 Has_Created_Identifier => True,
6111                 Is_Asynchronous_Call_Block => True);
6112
6113             --  Append call to if Enqueue (When, DB'Unchecked_Access) then
6114
6115             Rewrite (Ecall,
6116               Make_Implicit_If_Statement (N,
6117                 Condition => Make_Function_Call (Loc,
6118                   Name => Enqueue_Call,
6119                   Parameter_Associations => Parameter_Associations (Ecall)),
6120                 Then_Statements =>
6121                   New_List (Make_Block_Statement (Loc,
6122                     Handled_Statement_Sequence =>
6123                       Make_Handled_Sequence_Of_Statements (Loc,
6124                         Statements => New_List (
6125                           Make_Implicit_Label_Declaration (Loc,
6126                             Defining_Identifier => Blk_Ent,
6127                             Label_Construct     => Abortable_Block),
6128                           Abortable_Block),
6129                         Exception_Handlers => Hdle)))));
6130
6131             Stmts := New_List (Ecall);
6132
6133             --  Construct statement sequence for new block
6134
6135             Append_To (Stmts,
6136               Make_Implicit_If_Statement (N,
6137                 Condition => Make_Function_Call (Loc,
6138                   Name => New_Reference_To (
6139                     RTE (RE_Timed_Out), Loc),
6140                   Parameter_Associations => New_List (
6141                     Make_Attribute_Reference (Loc,
6142                       Prefix => New_Reference_To (Dblock_Ent, Loc),
6143                       Attribute_Name => Name_Unchecked_Access))),
6144                 Then_Statements => Tstats));
6145
6146             --  The result is the new block
6147
6148             Set_Entry_Cancel_Parameter (Blk_Ent, Dblock_Ent);
6149
6150             Rewrite (N,
6151               Make_Block_Statement (Loc,
6152                 Declarations => New_List (
6153                   Make_Object_Declaration (Loc,
6154                     Defining_Identifier => Dblock_Ent,
6155                     Aliased_Present => True,
6156                     Object_Definition => New_Reference_To (
6157                       RTE (RE_Delay_Block), Loc))),
6158
6159                 Handled_Statement_Sequence =>
6160                   Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6161
6162             Analyze (N);
6163             return;
6164          end if;
6165
6166       else
6167          N_Orig := N;
6168       end if;
6169
6170       Extract_Entry (Ecall, Concval, Ename, Index);
6171       Build_Simple_Entry_Call (Ecall, Concval, Ename, Index);
6172
6173       Stmts := Statements (Handled_Statement_Sequence (Ecall));
6174       Decls := Declarations (Ecall);
6175
6176       if Is_Protected_Type (Etype (Concval)) then
6177
6178          --  Get the declarations of the block expanded from the entry call
6179
6180          Decl := First (Decls);
6181          while Present (Decl)
6182            and then
6183              (Nkind (Decl) /= N_Object_Declaration
6184                or else not Is_RTE (Etype (Object_Definition (Decl)),
6185                                    RE_Communication_Block))
6186          loop
6187             Next (Decl);
6188          end loop;
6189
6190          pragma Assert (Present (Decl));
6191          Cancel_Param := Defining_Identifier (Decl);
6192
6193          --  Change the mode of the Protected_Entry_Call call
6194
6195          --  Protected_Entry_Call (
6196          --    Object => po._object'Access,
6197          --    E => <entry index>;
6198          --    Uninterpreted_Data => P'Address;
6199          --    Mode => Asynchronous_Call;
6200          --    Block => Bnn);
6201
6202          Stmt := First (Stmts);
6203
6204          --  Skip assignments to temporaries created for in-out parameters
6205
6206          --  This makes unwarranted assumptions about the shape of the expanded
6207          --  tree for the call, and should be cleaned up ???
6208
6209          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6210             Next (Stmt);
6211          end loop;
6212
6213          Call := Stmt;
6214
6215          Param := First (Parameter_Associations (Call));
6216          while Present (Param)
6217            and then not Is_RTE (Etype (Param), RE_Call_Modes)
6218          loop
6219             Next (Param);
6220          end loop;
6221
6222          pragma Assert (Present (Param));
6223          Rewrite (Param, New_Reference_To (RTE (RE_Asynchronous_Call), Loc));
6224          Analyze (Param);
6225
6226          --  Append an if statement to execute the abortable part
6227
6228          --  Generate:
6229          --    if Enqueued (Bnn) then
6230
6231          Append_To (Stmts,
6232            Make_Implicit_If_Statement (N,
6233              Condition => Make_Function_Call (Loc,
6234                Name => New_Reference_To (
6235                  RTE (RE_Enqueued), Loc),
6236                Parameter_Associations => New_List (
6237                  New_Reference_To (Cancel_Param, Loc))),
6238              Then_Statements => Astats));
6239
6240          Abortable_Block :=
6241            Make_Block_Statement (Loc,
6242              Identifier => New_Reference_To (Blk_Ent, Loc),
6243              Handled_Statement_Sequence =>
6244                Make_Handled_Sequence_Of_Statements (Loc,
6245                  Statements => Stmts),
6246              Has_Created_Identifier => True,
6247              Is_Asynchronous_Call_Block => True);
6248
6249          --  For the VM call Update_Exception instead of Abort_Undefer.
6250          --  See 4jexcept.ads for an explanation.
6251
6252          if VM_Target = No_VM then
6253             Target_Undefer := RE_Abort_Undefer;
6254          else
6255             Target_Undefer := RE_Update_Exception;
6256             Undefer_Args :=
6257               New_List (Make_Function_Call (Loc,
6258                           Name => New_Occurrence_Of
6259                                     (RTE (RE_Current_Target_Exception), Loc)));
6260          end if;
6261
6262          Stmts := New_List (
6263            Make_Block_Statement (Loc,
6264              Handled_Statement_Sequence =>
6265                Make_Handled_Sequence_Of_Statements (Loc,
6266                  Statements => New_List (
6267                    Make_Implicit_Label_Declaration (Loc,
6268                      Defining_Identifier => Blk_Ent,
6269                      Label_Construct     => Abortable_Block),
6270                    Abortable_Block),
6271
6272                --  exception
6273
6274                  Exception_Handlers => New_List (
6275                    Make_Implicit_Exception_Handler (Loc,
6276
6277                --  when Abort_Signal =>
6278                --     Abort_Undefer.all;
6279
6280                      Exception_Choices =>
6281                        New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6282                      Statements => New_List (
6283                        Make_Procedure_Call_Statement (Loc,
6284                          Name => New_Reference_To (
6285                            RTE (Target_Undefer), Loc),
6286                          Parameter_Associations => Undefer_Args)))))),
6287
6288          --  if not Cancelled (Bnn) then
6289          --     triggered statements
6290          --  end if;
6291
6292            Make_Implicit_If_Statement (N,
6293              Condition => Make_Op_Not (Loc,
6294                Right_Opnd =>
6295                  Make_Function_Call (Loc,
6296                    Name => New_Occurrence_Of (RTE (RE_Cancelled), Loc),
6297                    Parameter_Associations => New_List (
6298                      New_Occurrence_Of (Cancel_Param, Loc)))),
6299              Then_Statements => Tstats));
6300
6301       --  Asynchronous task entry call
6302
6303       else
6304          if No (Decls) then
6305             Decls := New_List;
6306          end if;
6307
6308          B := Make_Defining_Identifier (Loc, Name_uB);
6309
6310          --  Insert declaration of B in declarations of existing block
6311
6312          Prepend_To (Decls,
6313            Make_Object_Declaration (Loc,
6314              Defining_Identifier => B,
6315              Object_Definition => New_Reference_To (Standard_Boolean, Loc)));
6316
6317          Cancel_Param := Make_Defining_Identifier (Loc, Name_uC);
6318
6319          --  Insert declaration of C in declarations of existing block
6320
6321          Prepend_To (Decls,
6322            Make_Object_Declaration (Loc,
6323              Defining_Identifier => Cancel_Param,
6324              Object_Definition => New_Reference_To (Standard_Boolean, Loc)));
6325
6326          --  Remove and save the call to Call_Simple
6327
6328          Stmt := First (Stmts);
6329
6330          --  Skip assignments to temporaries created for in-out parameters.
6331          --  This makes unwarranted assumptions about the shape of the expanded
6332          --  tree for the call, and should be cleaned up ???
6333
6334          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6335             Next (Stmt);
6336          end loop;
6337
6338          Call := Stmt;
6339
6340          --  Create the inner block to protect the abortable part
6341
6342          Hdle :=  New_List (
6343            Make_Implicit_Exception_Handler (Loc,
6344              Exception_Choices =>
6345                New_List (New_Reference_To (Stand.Abort_Signal, Loc)),
6346              Statements =>
6347                New_List (
6348                  Make_Procedure_Call_Statement (Loc,
6349                    Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)))));
6350
6351          Prepend_To (Astats,
6352            Make_Procedure_Call_Statement (Loc,
6353              Name => New_Reference_To (RTE (RE_Abort_Undefer), Loc)));
6354
6355          Abortable_Block :=
6356            Make_Block_Statement (Loc,
6357              Identifier => New_Reference_To (Blk_Ent, Loc),
6358              Handled_Statement_Sequence =>
6359                Make_Handled_Sequence_Of_Statements (Loc,
6360                  Statements => Astats),
6361              Has_Created_Identifier => True,
6362              Is_Asynchronous_Call_Block => True);
6363
6364          Insert_After (Call,
6365            Make_Block_Statement (Loc,
6366              Handled_Statement_Sequence =>
6367                Make_Handled_Sequence_Of_Statements (Loc,
6368                  Statements => New_List (
6369                    Make_Implicit_Label_Declaration (Loc,
6370                      Defining_Identifier =>
6371                        Blk_Ent,
6372                      Label_Construct =>
6373                        Abortable_Block),
6374                    Abortable_Block),
6375                  Exception_Handlers => Hdle)));
6376
6377          --  Create new call statement
6378
6379          Params := Parameter_Associations (Call);
6380
6381          Append_To (Params,
6382            New_Reference_To (RTE (RE_Asynchronous_Call), Loc));
6383          Append_To (Params,
6384            New_Reference_To (B, Loc));
6385
6386          Rewrite (Call,
6387            Make_Procedure_Call_Statement (Loc,
6388              Name =>
6389                New_Reference_To (RTE (RE_Task_Entry_Call), Loc),
6390              Parameter_Associations => Params));
6391
6392          --  Construct statement sequence for new block
6393
6394          Append_To (Stmts,
6395            Make_Implicit_If_Statement (N,
6396              Condition =>
6397                Make_Op_Not (Loc,
6398                  New_Reference_To (Cancel_Param, Loc)),
6399              Then_Statements => Tstats));
6400
6401          --  Protected the call against abort
6402
6403          Prepend_To (Stmts,
6404            Make_Procedure_Call_Statement (Loc,
6405              Name => New_Reference_To (RTE (RE_Abort_Defer), Loc),
6406              Parameter_Associations => Empty_List));
6407       end if;
6408
6409       Set_Entry_Cancel_Parameter (Blk_Ent, Cancel_Param);
6410
6411       --  The result is the new block
6412
6413       Rewrite (N_Orig,
6414         Make_Block_Statement (Loc,
6415           Declarations => Decls,
6416           Handled_Statement_Sequence =>
6417             Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6418
6419       Analyze (N_Orig);
6420    end Expand_N_Asynchronous_Select;
6421
6422    -------------------------------------
6423    -- Expand_N_Conditional_Entry_Call --
6424    -------------------------------------
6425
6426    --  The conditional task entry call is converted to a call to
6427    --  Task_Entry_Call:
6428
6429    --    declare
6430    --       B : Boolean;
6431    --       P : parms := (parm, parm, parm);
6432
6433    --    begin
6434    --       Task_Entry_Call
6435    --         (<acceptor-task>,   --  Acceptor
6436    --          <entry-index>,     --  E
6437    --          P'Address,         --  Uninterpreted_Data
6438    --          Conditional_Call,  --  Mode
6439    --          B);                --  Rendezvous_Successful
6440    --       parm := P.param;
6441    --       parm := P.param;
6442    --       ...
6443    --       if B then
6444    --          normal-statements
6445    --       else
6446    --          else-statements
6447    --       end if;
6448    --    end;
6449
6450    --  For a description of the use of P and the assignments after the call,
6451    --  see Expand_N_Entry_Call_Statement. Note that the entry call of the
6452    --  conditional entry call has already been expanded (by the Expand_N_Entry
6453    --  _Call_Statement procedure) as follows:
6454
6455    --    declare
6456    --       P : parms := (parm, parm, parm);
6457    --    begin
6458    --       ... info for in-out parameters
6459    --       Call_Simple (acceptor-task, entry-index, P'Address);
6460    --       parm := P.param;
6461    --       parm := P.param;
6462    --       ...
6463    --    end;
6464
6465    --  so the task at hand is to convert the latter expansion into the former
6466
6467    --  The conditional protected entry call is converted to a call to
6468    --  Protected_Entry_Call:
6469
6470    --    declare
6471    --       P : parms := (parm, parm, parm);
6472    --       Bnn : Communications_Block;
6473
6474    --    begin
6475    --       Protected_Entry_Call
6476    --         (po._object'Access,  --  Object
6477    --          <entry index>,      --  E
6478    --          P'Address,          --  Uninterpreted_Data
6479    --          Conditional_Call,   --  Mode
6480    --          Bnn);               --  Block
6481    --       parm := P.param;
6482    --       parm := P.param;
6483    --       ...
6484    --       if Cancelled (Bnn) then
6485    --          else-statements
6486    --       else
6487    --          normal-statements
6488    --       end if;
6489    --    end;
6490
6491    --  Ada 2005 (AI-345): A dispatching conditional entry call is converted
6492    --  into:
6493
6494    --    declare
6495    --       B : Boolean := False;
6496    --       C : Ada.Tags.Prim_Op_Kind;
6497    --       K : Ada.Tags.Tagged_Kind :=
6498    --             Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
6499    --       P : Parameters := (Param1 .. ParamN);
6500    --       S : Integer;
6501
6502    --    begin
6503    --       if K = Ada.Tags.TK_Limited_Tagged then
6504    --          <dispatching-call>;
6505    --          <triggering-statements>
6506
6507    --       else
6508    --          S :=
6509    --            Ada.Tags.Get_Offset_Index
6510    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
6511
6512    --          _Disp_Conditional_Select (<object>, S, P'Address, C, B);
6513
6514    --          if C = POK_Protected_Entry
6515    --            or else C = POK_Task_Entry
6516    --          then
6517    --             Param1 := P.Param1;
6518    --             ...
6519    --             ParamN := P.ParamN;
6520    --          end if;
6521
6522    --          if B then
6523    --             if C = POK_Procedure
6524    --               or else C = POK_Protected_Procedure
6525    --               or else C = POK_Task_Procedure
6526    --             then
6527    --                <dispatching-call>;
6528    --             end if;
6529
6530    --             <triggering-statements>
6531    --          else
6532    --             <else-statements>
6533    --          end if;
6534    --       end if;
6535    --    end;
6536
6537    procedure Expand_N_Conditional_Entry_Call (N : Node_Id) is
6538       Loc : constant Source_Ptr := Sloc (N);
6539       Alt : constant Node_Id    := Entry_Call_Alternative (N);
6540       Blk : Node_Id             := Entry_Call_Statement (Alt);
6541
6542       Actuals        : List_Id;
6543       Blk_Typ        : Entity_Id;
6544       Call           : Node_Id;
6545       Call_Ent       : Entity_Id;
6546       Conc_Typ_Stmts : List_Id;
6547       Decl           : Node_Id;
6548       Decls          : List_Id;
6549       Formals        : List_Id;
6550       Lim_Typ_Stmts  : List_Id;
6551       N_Stats        : List_Id;
6552       Obj            : Entity_Id;
6553       Param          : Node_Id;
6554       Params         : List_Id;
6555       Stmt           : Node_Id;
6556       Stmts          : List_Id;
6557       Transient_Blk  : Node_Id;
6558       Unpack         : List_Id;
6559
6560       B : Entity_Id;  --  Call status flag
6561       C : Entity_Id;  --  Call kind
6562       K : Entity_Id;  --  Tagged kind
6563       P : Entity_Id;  --  Parameter block
6564       S : Entity_Id;  --  Primitive operation slot
6565
6566    begin
6567       if Ada_Version >= Ada_05
6568         and then Nkind (Blk) = N_Procedure_Call_Statement
6569       then
6570          Extract_Dispatching_Call (Blk, Call_Ent, Obj, Actuals, Formals);
6571
6572          Decls := New_List;
6573          Stmts := New_List;
6574
6575          --  Call status flag processing, generate:
6576          --    B : Boolean := False;
6577
6578          B := Build_B (Loc, Decls);
6579
6580          --  Call kind processing, generate:
6581          --    C : Ada.Tags.Prim_Op_Kind;
6582
6583          C := Build_C (Loc, Decls);
6584
6585          --  Tagged kind processing, generate:
6586          --    K : Ada.Tags.Tagged_Kind :=
6587          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
6588
6589          K := Build_K (Loc, Decls, Obj);
6590
6591          --  Parameter block processing
6592
6593          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
6594          P       := Parameter_Block_Pack
6595                       (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
6596
6597          --  Dispatch table slot processing, generate:
6598          --    S : Integer;
6599
6600          S := Build_S (Loc, Decls);
6601
6602          --  Generate:
6603          --    S := Ada.Tags.Get_Offset_Index
6604          --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
6605
6606          Conc_Typ_Stmts :=
6607            New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
6608
6609          --  Generate:
6610          --    _Disp_Conditional_Select (<object>, S, P'Address, C, B);
6611
6612          Append_To (Conc_Typ_Stmts,
6613            Make_Procedure_Call_Statement (Loc,
6614              Name =>
6615                New_Reference_To (
6616                  Find_Prim_Op (Etype (Etype (Obj)),
6617                    Name_uDisp_Conditional_Select),
6618                  Loc),
6619              Parameter_Associations =>
6620                New_List (
6621                  New_Copy_Tree (Obj),            --  <object>
6622                  New_Reference_To (S, Loc),      --  S
6623                  Make_Attribute_Reference (Loc,  --  P'Address
6624                    Prefix =>
6625                      New_Reference_To (P, Loc),
6626                    Attribute_Name =>
6627                      Name_Address),
6628                  New_Reference_To (C, Loc),      --  C
6629                  New_Reference_To (B, Loc))));   --  B
6630
6631          --  Generate:
6632          --    if C = POK_Protected_Entry
6633          --      or else C = POK_Task_Entry
6634          --    then
6635          --       Param1 := P.Param1;
6636          --       ...
6637          --       ParamN := P.ParamN;
6638          --    end if;
6639
6640          Unpack := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
6641
6642          --  Generate the if statement only when the packed parameters need
6643          --  explicit assignments to their corresponding actuals.
6644
6645          if Present (Unpack) then
6646             Append_To (Conc_Typ_Stmts,
6647               Make_If_Statement (Loc,
6648
6649                 Condition =>
6650                   Make_Or_Else (Loc,
6651                     Left_Opnd =>
6652                       Make_Op_Eq (Loc,
6653                         Left_Opnd =>
6654                           New_Reference_To (C, Loc),
6655                         Right_Opnd =>
6656                           New_Reference_To (RTE (
6657                             RE_POK_Protected_Entry), Loc)),
6658                     Right_Opnd =>
6659                       Make_Op_Eq (Loc,
6660                         Left_Opnd =>
6661                           New_Reference_To (C, Loc),
6662                         Right_Opnd =>
6663                           New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
6664
6665                  Then_Statements =>
6666                    Unpack));
6667          end if;
6668
6669          --  Generate:
6670          --    if B then
6671          --       if C = POK_Procedure
6672          --         or else C = POK_Protected_Procedure
6673          --         or else C = POK_Task_Procedure
6674          --       then
6675          --          <dispatching-call>
6676          --       end if;
6677          --       <normal-statements>
6678          --    else
6679          --       <else-statements>
6680          --    end if;
6681
6682          N_Stats := New_Copy_List_Tree (Statements (Alt));
6683
6684          Prepend_To (N_Stats,
6685            Make_If_Statement (Loc,
6686              Condition =>
6687                Make_Or_Else (Loc,
6688                  Left_Opnd =>
6689                    Make_Op_Eq (Loc,
6690                      Left_Opnd =>
6691                        New_Reference_To (C, Loc),
6692                      Right_Opnd =>
6693                        New_Reference_To (RTE (RE_POK_Procedure), Loc)),
6694
6695                  Right_Opnd =>
6696                    Make_Or_Else (Loc,
6697                      Left_Opnd =>
6698                        Make_Op_Eq (Loc,
6699                          Left_Opnd =>
6700                            New_Reference_To (C, Loc),
6701                          Right_Opnd =>
6702                            New_Reference_To (RTE (
6703                              RE_POK_Protected_Procedure), Loc)),
6704
6705                      Right_Opnd =>
6706                        Make_Op_Eq (Loc,
6707                          Left_Opnd =>
6708                            New_Reference_To (C, Loc),
6709                          Right_Opnd =>
6710                            New_Reference_To (RTE (
6711                              RE_POK_Task_Procedure), Loc)))),
6712
6713              Then_Statements =>
6714                New_List (Blk)));
6715
6716          Append_To (Conc_Typ_Stmts,
6717            Make_If_Statement (Loc,
6718              Condition => New_Reference_To (B, Loc),
6719              Then_Statements => N_Stats,
6720              Else_Statements => Else_Statements (N)));
6721
6722          --  Generate:
6723          --    <dispatching-call>;
6724          --    <triggering-statements>
6725
6726          Lim_Typ_Stmts := New_Copy_List_Tree (Statements (Alt));
6727          Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (Blk));
6728
6729          --  Generate:
6730          --    if K = Ada.Tags.TK_Limited_Tagged then
6731          --       Lim_Typ_Stmts
6732          --    else
6733          --       Conc_Typ_Stmts
6734          --    end if;
6735
6736          Append_To (Stmts,
6737            Make_If_Statement (Loc,
6738              Condition =>
6739                Make_Op_Eq (Loc,
6740                  Left_Opnd =>
6741                    New_Reference_To (K, Loc),
6742                  Right_Opnd =>
6743                    New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
6744
6745              Then_Statements =>
6746                Lim_Typ_Stmts,
6747
6748              Else_Statements =>
6749                Conc_Typ_Stmts));
6750
6751          Rewrite (N,
6752            Make_Block_Statement (Loc,
6753              Declarations =>
6754                Decls,
6755              Handled_Statement_Sequence =>
6756                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6757
6758       --  As described above, The entry alternative is transformed into a
6759       --  block that contains the gnulli call, and possibly assignment
6760       --  statements for in-out parameters. The gnulli call may itself be
6761       --  rewritten into a transient block if some unconstrained parameters
6762       --  require it. We need to retrieve the call to complete its parameter
6763       --  list.
6764
6765       else
6766          Transient_Blk :=
6767            First_Real_Statement (Handled_Statement_Sequence (Blk));
6768
6769          if Present (Transient_Blk)
6770            and then Nkind (Transient_Blk) = N_Block_Statement
6771          then
6772             Blk := Transient_Blk;
6773          end if;
6774
6775          Stmts := Statements (Handled_Statement_Sequence (Blk));
6776          Stmt  := First (Stmts);
6777          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
6778             Next (Stmt);
6779          end loop;
6780
6781          Call   := Stmt;
6782          Params := Parameter_Associations (Call);
6783
6784          if Is_RTE (Entity (Name (Call)), RE_Protected_Entry_Call) then
6785
6786             --  Substitute Conditional_Entry_Call for Simple_Call parameter
6787
6788             Param := First (Params);
6789             while Present (Param)
6790               and then not Is_RTE (Etype (Param), RE_Call_Modes)
6791             loop
6792                Next (Param);
6793             end loop;
6794
6795             pragma Assert (Present (Param));
6796             Rewrite (Param, New_Reference_To (RTE (RE_Conditional_Call), Loc));
6797
6798             Analyze (Param);
6799
6800             --  Find the Communication_Block parameter for the call to the
6801             --  Cancelled function.
6802
6803             Decl := First (Declarations (Blk));
6804             while Present (Decl)
6805               and then not Is_RTE (Etype (Object_Definition (Decl)),
6806                              RE_Communication_Block)
6807             loop
6808                Next (Decl);
6809             end loop;
6810
6811             --  Add an if statement to execute the else part if the call
6812             --  does not succeed (as indicated by the Cancelled predicate).
6813
6814             Append_To (Stmts,
6815               Make_Implicit_If_Statement (N,
6816                 Condition => Make_Function_Call (Loc,
6817                   Name => New_Reference_To (RTE (RE_Cancelled), Loc),
6818                   Parameter_Associations => New_List (
6819                     New_Reference_To (Defining_Identifier (Decl), Loc))),
6820                 Then_Statements => Else_Statements (N),
6821                 Else_Statements => Statements (Alt)));
6822
6823          else
6824             B := Make_Defining_Identifier (Loc, Name_uB);
6825
6826             --  Insert declaration of B in declarations of existing block
6827
6828             if No (Declarations (Blk)) then
6829                Set_Declarations (Blk, New_List);
6830             end if;
6831
6832             Prepend_To (Declarations (Blk),
6833               Make_Object_Declaration (Loc,
6834                 Defining_Identifier => B,
6835                 Object_Definition =>
6836                   New_Reference_To (Standard_Boolean, Loc)));
6837
6838             --  Create new call statement
6839
6840             Append_To (Params,
6841               New_Reference_To (RTE (RE_Conditional_Call), Loc));
6842             Append_To (Params, New_Reference_To (B, Loc));
6843
6844             Rewrite (Call,
6845               Make_Procedure_Call_Statement (Loc,
6846                 Name => New_Reference_To (RTE (RE_Task_Entry_Call), Loc),
6847                 Parameter_Associations => Params));
6848
6849             --  Construct statement sequence for new block
6850
6851             Append_To (Stmts,
6852               Make_Implicit_If_Statement (N,
6853                 Condition => New_Reference_To (B, Loc),
6854                 Then_Statements => Statements (Alt),
6855                 Else_Statements => Else_Statements (N)));
6856          end if;
6857
6858          --  The result is the new block
6859
6860          Rewrite (N,
6861            Make_Block_Statement (Loc,
6862              Declarations => Declarations (Blk),
6863              Handled_Statement_Sequence =>
6864                Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
6865       end if;
6866
6867       Analyze (N);
6868    end Expand_N_Conditional_Entry_Call;
6869
6870    ---------------------------------------
6871    -- Expand_N_Delay_Relative_Statement --
6872    ---------------------------------------
6873
6874    --  Delay statement is implemented as a procedure call to Delay_For
6875    --  defined in Ada.Calendar.Delays in order to reduce the overhead of
6876    --  simple delays imposed by the use of Protected Objects.
6877
6878    procedure Expand_N_Delay_Relative_Statement (N : Node_Id) is
6879       Loc : constant Source_Ptr := Sloc (N);
6880    begin
6881       Rewrite (N,
6882         Make_Procedure_Call_Statement (Loc,
6883           Name => New_Reference_To (RTE (RO_CA_Delay_For), Loc),
6884           Parameter_Associations => New_List (Expression (N))));
6885       Analyze (N);
6886    end Expand_N_Delay_Relative_Statement;
6887
6888    ------------------------------------
6889    -- Expand_N_Delay_Until_Statement --
6890    ------------------------------------
6891
6892    --  Delay Until statement is implemented as a procedure call to
6893    --  Delay_Until defined in Ada.Calendar.Delays and Ada.Real_Time.Delays.
6894
6895    procedure Expand_N_Delay_Until_Statement (N : Node_Id) is
6896       Loc : constant Source_Ptr := Sloc (N);
6897       Typ : Entity_Id;
6898
6899    begin
6900       if Is_RTE (Base_Type (Etype (Expression (N))), RO_CA_Time) then
6901          Typ := RTE (RO_CA_Delay_Until);
6902       else
6903          Typ := RTE (RO_RT_Delay_Until);
6904       end if;
6905
6906       Rewrite (N,
6907         Make_Procedure_Call_Statement (Loc,
6908           Name => New_Reference_To (Typ, Loc),
6909           Parameter_Associations => New_List (Expression (N))));
6910
6911       Analyze (N);
6912    end Expand_N_Delay_Until_Statement;
6913
6914    -------------------------
6915    -- Expand_N_Entry_Body --
6916    -------------------------
6917
6918    procedure Expand_N_Entry_Body (N : Node_Id) is
6919    begin
6920       --  Associate discriminals with the next protected operation body to be
6921       --  expanded.
6922
6923       if Present (Next_Protected_Operation (N)) then
6924          Set_Discriminals (Parent (Current_Scope));
6925       end if;
6926    end Expand_N_Entry_Body;
6927
6928    -----------------------------------
6929    -- Expand_N_Entry_Call_Statement --
6930    -----------------------------------
6931
6932    --  An entry call is expanded into GNARLI calls to implement a simple entry
6933    --  call (see Build_Simple_Entry_Call).
6934
6935    procedure Expand_N_Entry_Call_Statement (N : Node_Id) is
6936       Concval : Node_Id;
6937       Ename   : Node_Id;
6938       Index   : Node_Id;
6939
6940    begin
6941       if No_Run_Time_Mode then
6942          Error_Msg_CRT ("entry call", N);
6943          return;
6944       end if;
6945
6946       --  If this entry call is part of an asynchronous select, don't expand it
6947       --  here; it will be expanded with the select statement. Don't expand
6948       --  timed entry calls either, as they are translated into asynchronous
6949       --  entry calls.
6950
6951       --  ??? This whole approach is questionable; it may be better to go back
6952       --  to allowing the expansion to take place and then attempting to fix it
6953       --  up in Expand_N_Asynchronous_Select. The tricky part is figuring out
6954       --  whether the expanded call is on a task or protected entry.
6955
6956       if (Nkind (Parent (N)) /= N_Triggering_Alternative
6957            or else N /= Triggering_Statement (Parent (N)))
6958         and then (Nkind (Parent (N)) /= N_Entry_Call_Alternative
6959                    or else N /= Entry_Call_Statement (Parent (N))
6960                    or else Nkind (Parent (Parent (N))) /= N_Timed_Entry_Call)
6961       then
6962          Extract_Entry (N, Concval, Ename, Index);
6963          Build_Simple_Entry_Call (N, Concval, Ename, Index);
6964       end if;
6965    end Expand_N_Entry_Call_Statement;
6966
6967    --------------------------------
6968    -- Expand_N_Entry_Declaration --
6969    --------------------------------
6970
6971    --  If there are parameters, then first, each of the formals is marked by
6972    --  setting Is_Entry_Formal. Next a record type is built which is used to
6973    --  hold the parameter values. The name of this record type is entryP where
6974    --  entry is the name of the entry, with an additional corresponding access
6975    --  type called entryPA. The record type has matching components for each
6976    --  formal (the component names are the same as the formal names). For
6977    --  elementary types, the component type matches the formal type. For
6978    --  composite types, an access type is declared (with the name formalA)
6979    --  which designates the formal type, and the type of the component is this
6980    --  access type. Finally the Entry_Component of each formal is set to
6981    --  reference the corresponding record component.
6982
6983    procedure Expand_N_Entry_Declaration (N : Node_Id) is
6984       Loc        : constant Source_Ptr := Sloc (N);
6985       Entry_Ent  : constant Entity_Id  := Defining_Identifier (N);
6986       Components : List_Id;
6987       Formal     : Node_Id;
6988       Ftype      : Entity_Id;
6989       Last_Decl  : Node_Id;
6990       Component  : Entity_Id;
6991       Ctype      : Entity_Id;
6992       Decl       : Node_Id;
6993       Rec_Ent    : Entity_Id;
6994       Acc_Ent    : Entity_Id;
6995
6996    begin
6997       Formal := First_Formal (Entry_Ent);
6998       Last_Decl := N;
6999
7000       --  Most processing is done only if parameters are present
7001
7002       if Present (Formal) then
7003          Components := New_List;
7004
7005          --  Loop through formals
7006
7007          while Present (Formal) loop
7008             Set_Is_Entry_Formal (Formal);
7009             Component :=
7010               Make_Defining_Identifier (Sloc (Formal), Chars (Formal));
7011             Set_Entry_Component (Formal, Component);
7012             Set_Entry_Formal (Component, Formal);
7013             Ftype := Etype (Formal);
7014
7015             --  Declare new access type and then append
7016
7017             Ctype :=
7018               Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
7019
7020             Decl :=
7021               Make_Full_Type_Declaration (Loc,
7022                 Defining_Identifier => Ctype,
7023                 Type_Definition     =>
7024                   Make_Access_To_Object_Definition (Loc,
7025                     All_Present        => True,
7026                     Constant_Present   => Ekind (Formal) = E_In_Parameter,
7027                     Subtype_Indication => New_Reference_To (Ftype, Loc)));
7028
7029             Insert_After (Last_Decl, Decl);
7030             Last_Decl := Decl;
7031
7032             Append_To (Components,
7033               Make_Component_Declaration (Loc,
7034                 Defining_Identifier => Component,
7035                 Component_Definition =>
7036                   Make_Component_Definition (Loc,
7037                     Aliased_Present    => False,
7038                     Subtype_Indication => New_Reference_To (Ctype, Loc))));
7039
7040             Next_Formal_With_Extras (Formal);
7041          end loop;
7042
7043          --  Create the Entry_Parameter_Record declaration
7044
7045          Rec_Ent :=
7046            Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
7047
7048          Decl :=
7049            Make_Full_Type_Declaration (Loc,
7050              Defining_Identifier => Rec_Ent,
7051              Type_Definition     =>
7052                Make_Record_Definition (Loc,
7053                  Component_List =>
7054                    Make_Component_List (Loc,
7055                      Component_Items => Components)));
7056
7057          Insert_After (Last_Decl, Decl);
7058          Last_Decl := Decl;
7059
7060          --  Construct and link in the corresponding access type
7061
7062          Acc_Ent :=
7063            Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
7064
7065          Set_Entry_Parameters_Type (Entry_Ent, Acc_Ent);
7066
7067          Decl :=
7068            Make_Full_Type_Declaration (Loc,
7069              Defining_Identifier => Acc_Ent,
7070              Type_Definition     =>
7071                Make_Access_To_Object_Definition (Loc,
7072                  All_Present        => True,
7073                  Subtype_Indication => New_Reference_To (Rec_Ent, Loc)));
7074
7075          Insert_After (Last_Decl, Decl);
7076          Last_Decl := Decl;
7077       end if;
7078    end Expand_N_Entry_Declaration;
7079
7080    -----------------------------
7081    -- Expand_N_Protected_Body --
7082    -----------------------------
7083
7084    --  Protected bodies are expanded to the completion of the subprograms
7085    --  created for the corresponding protected type. These are a protected and
7086    --  unprotected version of each protected subprogram in the object, a
7087    --  function to calculate each entry barrier, and a procedure to execute the
7088    --  sequence of statements of each protected entry body. For example, for
7089    --  protected type ptype:
7090
7091    --  function entB
7092    --    (O : System.Address;
7093    --     E : Protected_Entry_Index)
7094    --     return Boolean
7095    --  is
7096    --     <discriminant renamings>
7097    --     <private object renamings>
7098    --  begin
7099    --     return <barrier expression>;
7100    --  end entB;
7101
7102    --  procedure pprocN (_object : in out poV;...) is
7103    --     <discriminant renamings>
7104    --     <private object renamings>
7105    --  begin
7106    --     <sequence of statements>
7107    --  end pprocN;
7108
7109    --  procedure pprocP (_object : in out poV;...) is
7110    --     procedure _clean is
7111    --       Pn : Boolean;
7112    --     begin
7113    --       ptypeS (_object, Pn);
7114    --       Unlock (_object._object'Access);
7115    --       Abort_Undefer.all;
7116    --     end _clean;
7117
7118    --  begin
7119    --     Abort_Defer.all;
7120    --     Lock (_object._object'Access);
7121    --     pprocN (_object;...);
7122    --  at end
7123    --     _clean;
7124    --  end pproc;
7125
7126    --  function pfuncN (_object : poV;...) return Return_Type is
7127    --     <discriminant renamings>
7128    --     <private object renamings>
7129    --  begin
7130    --     <sequence of statements>
7131    --  end pfuncN;
7132
7133    --  function pfuncP (_object : poV) return Return_Type is
7134    --     procedure _clean is
7135    --     begin
7136    --        Unlock (_object._object'Access);
7137    --        Abort_Undefer.all;
7138    --     end _clean;
7139
7140    --  begin
7141    --     Abort_Defer.all;
7142    --     Lock (_object._object'Access);
7143    --     return pfuncN (_object);
7144
7145    --  at end
7146    --     _clean;
7147    --  end pfunc;
7148
7149    --  procedure entE
7150    --    (O : System.Address;
7151    --     P : System.Address;
7152    --     E : Protected_Entry_Index)
7153    --  is
7154    --     <discriminant renamings>
7155    --     <private object renamings>
7156    --     type poVP is access poV;
7157    --     _Object : ptVP := ptVP!(O);
7158
7159    --  begin
7160    --     begin
7161    --        <statement sequence>
7162    --        Complete_Entry_Body (_Object._Object);
7163    --     exception
7164    --        when all others =>
7165    --           Exceptional_Complete_Entry_Body (
7166    --             _Object._Object, Get_GNAT_Exception);
7167    --     end;
7168    --  end entE;
7169
7170    --  The type poV is the record created for the protected type to hold
7171    --  the state of the protected object.
7172
7173    procedure Expand_N_Protected_Body (N : Node_Id) is
7174       Loc          : constant Source_Ptr := Sloc (N);
7175       Pid          : constant Entity_Id  := Corresponding_Spec (N);
7176
7177       Current_Node : Node_Id;
7178       Disp_Op_Body : Node_Id;
7179       New_Op_Body  : Node_Id;
7180       Num_Entries  : Natural := 0;
7181       Op_Body      : Node_Id;
7182       Op_Decl      : Node_Id;
7183       Op_Id        : Entity_Id;
7184
7185       Chain        : Entity_Id := Empty;
7186       --  Finalization chain that may be attached to new body
7187
7188       function Build_Dispatching_Subprogram_Body
7189         (N        : Node_Id;
7190          Pid      : Node_Id;
7191          Prot_Bod : Node_Id) return Node_Id;
7192       --  Build a dispatching version of the protected subprogram body. The
7193       --  newly generated subprogram contains a call to the original protected
7194       --  body. The following code is generated:
7195       --
7196       --  function <protected-function-name> (Param1 .. ParamN) return
7197       --    <return-type> is
7198       --  begin
7199       --     return <protected-function-name>P (Param1 .. ParamN);
7200       --  end <protected-function-name>;
7201       --
7202       --  or
7203       --
7204       --  procedure <protected-procedure-name> (Param1 .. ParamN) is
7205       --  begin
7206       --     <protected-procedure-name>P (Param1 .. ParamN);
7207       --  end <protected-procedure-name>
7208
7209       ---------------------------------------
7210       -- Build_Dispatching_Subprogram_Body --
7211       ---------------------------------------
7212
7213       function Build_Dispatching_Subprogram_Body
7214         (N        : Node_Id;
7215          Pid      : Node_Id;
7216          Prot_Bod : Node_Id) return Node_Id
7217       is
7218          Loc     : constant Source_Ptr := Sloc (N);
7219          Actuals : List_Id;
7220          Formal  : Node_Id;
7221          Spec    : Node_Id;
7222          Stmts   : List_Id;
7223
7224       begin
7225          --  Generate a specification without a letter suffix in order to
7226          --  override an interface function or procedure.
7227
7228          Spec :=
7229            Build_Protected_Sub_Specification (N, Pid, Dispatching_Mode);
7230
7231          --  The formal parameters become the actuals of the protected
7232          --  function or procedure call.
7233
7234          Actuals := New_List;
7235          Formal  := First (Parameter_Specifications (Spec));
7236          while Present (Formal) loop
7237             Append_To (Actuals,
7238               Make_Identifier (Loc, Chars (Defining_Identifier (Formal))));
7239
7240             Next (Formal);
7241          end loop;
7242
7243          if Nkind (Spec) = N_Procedure_Specification then
7244             Stmts :=
7245               New_List (
7246                 Make_Procedure_Call_Statement (Loc,
7247                   Name =>
7248                     New_Reference_To (Corresponding_Spec (Prot_Bod), Loc),
7249                   Parameter_Associations => Actuals));
7250          else
7251             pragma Assert (Nkind (Spec) = N_Function_Specification);
7252
7253             Stmts :=
7254               New_List (
7255                 Make_Simple_Return_Statement (Loc,
7256                   Expression =>
7257                     Make_Function_Call (Loc,
7258                       Name =>
7259                         New_Reference_To (Corresponding_Spec (Prot_Bod), Loc),
7260                       Parameter_Associations => Actuals)));
7261          end if;
7262
7263          return
7264            Make_Subprogram_Body (Loc,
7265              Declarations  => Empty_List,
7266              Specification => Spec,
7267              Handled_Statement_Sequence =>
7268                Make_Handled_Sequence_Of_Statements (Loc, Stmts));
7269       end Build_Dispatching_Subprogram_Body;
7270
7271    --  Start of processing for Expand_N_Protected_Body
7272
7273    begin
7274       if No_Run_Time_Mode then
7275          Error_Msg_CRT ("protected body", N);
7276          return;
7277       end if;
7278
7279       --  This is the proper body corresponding to a stub. The declarations
7280       --  must be inserted at the point of the stub, which in turn is in the
7281       --  declarative part of the parent unit.
7282
7283       if Nkind (Parent (N)) = N_Subunit then
7284          Current_Node := Corresponding_Stub (Parent (N));
7285       else
7286          Current_Node := N;
7287       end if;
7288
7289       Op_Body := First (Declarations (N));
7290
7291       --  The protected body is replaced with the bodies of its
7292       --  protected operations, and the declarations for internal objects
7293       --  that may have been created for entry family bounds.
7294
7295       Rewrite (N, Make_Null_Statement (Sloc (N)));
7296       Analyze (N);
7297
7298       while Present (Op_Body) loop
7299          case Nkind (Op_Body) is
7300             when N_Subprogram_Declaration =>
7301                null;
7302
7303             when N_Subprogram_Body =>
7304
7305                --  Do not create bodies for eliminated operations
7306
7307                if not Is_Eliminated (Defining_Entity (Op_Body))
7308                  and then not Is_Eliminated (Corresponding_Spec (Op_Body))
7309                then
7310                   New_Op_Body :=
7311                     Build_Unprotected_Subprogram_Body (Op_Body, Pid);
7312
7313                   --  Propagate the finalization chain to the new body. In the
7314                   --  unlikely event that the subprogram contains a declaration
7315                   --  or allocator for an object that requires finalization,
7316                   --  the corresponding chain is created when analyzing the
7317                   --  body, and attached to its entity. This entity is not
7318                   --  further elaborated, and so the chain properly belongs to
7319                   --  the newly created subprogram body.
7320
7321                   Chain :=
7322                     Finalization_Chain_Entity (Defining_Entity (Op_Body));
7323
7324                   if Present (Chain) then
7325                      Set_Finalization_Chain_Entity
7326                        (Protected_Body_Subprogram
7327                          (Corresponding_Spec (Op_Body)), Chain);
7328                      Set_Analyzed
7329                          (Handled_Statement_Sequence (New_Op_Body), False);
7330                   end if;
7331
7332                   Insert_After (Current_Node, New_Op_Body);
7333                   Current_Node := New_Op_Body;
7334                   Analyze (New_Op_Body);
7335
7336                   --  Build the corresponding protected operation. It may
7337                   --  appear that this is needed only if this is a visible
7338                   --  operation of the type, or if it is an interrupt handler,
7339                   --  and this was the strategy used previously in GNAT.
7340                   --  However, the operation may be exported through a 'Access
7341                   --  to an external caller. This is the common idiom in code
7342                   --  that uses the Ada 2005 Timing_Events package. As a result
7343                   --  we need to produce the protected body for both visible
7344                   --  and private operations.
7345
7346                   if Present (Corresponding_Spec (Op_Body)) then
7347                      Op_Decl :=
7348                        Unit_Declaration_Node (Corresponding_Spec (Op_Body));
7349
7350                      if Nkind (Parent (Op_Decl)) =
7351                           N_Protected_Definition
7352                      then
7353                         New_Op_Body :=
7354                           Build_Protected_Subprogram_Body (
7355                             Op_Body, Pid, Specification (New_Op_Body));
7356
7357                         Insert_After (Current_Node, New_Op_Body);
7358                         Analyze (New_Op_Body);
7359
7360                         Current_Node := New_Op_Body;
7361
7362                         --  Generate an overriding primitive operation body for
7363                         --  this subprogram if the protected type implements
7364                         --  an interface.
7365
7366                         if Ada_Version >= Ada_05
7367                           and then Present (Interfaces (
7368                                      Corresponding_Record_Type (Pid)))
7369                         then
7370                            Disp_Op_Body :=
7371                              Build_Dispatching_Subprogram_Body (
7372                                Op_Body, Pid, New_Op_Body);
7373
7374                            Insert_After (Current_Node, Disp_Op_Body);
7375                            Analyze (Disp_Op_Body);
7376
7377                            Current_Node := Disp_Op_Body;
7378                         end if;
7379                      end if;
7380                   end if;
7381                end if;
7382
7383             when N_Entry_Body =>
7384                Op_Id := Defining_Identifier (Op_Body);
7385                Num_Entries := Num_Entries + 1;
7386
7387                New_Op_Body := Build_Protected_Entry (Op_Body, Op_Id, Pid);
7388
7389                Insert_After (Current_Node, New_Op_Body);
7390                Current_Node := New_Op_Body;
7391                Analyze (New_Op_Body);
7392
7393             when N_Implicit_Label_Declaration =>
7394                null;
7395
7396             when N_Itype_Reference =>
7397                Insert_After (Current_Node, New_Copy (Op_Body));
7398
7399             when N_Freeze_Entity =>
7400                New_Op_Body := New_Copy (Op_Body);
7401
7402                if Present (Entity (Op_Body))
7403                  and then Freeze_Node (Entity (Op_Body)) = Op_Body
7404                then
7405                   Set_Freeze_Node (Entity (Op_Body), New_Op_Body);
7406                end if;
7407
7408                Insert_After (Current_Node, New_Op_Body);
7409                Current_Node := New_Op_Body;
7410                Analyze (New_Op_Body);
7411
7412             when N_Pragma =>
7413                New_Op_Body := New_Copy (Op_Body);
7414                Insert_After (Current_Node, New_Op_Body);
7415                Current_Node := New_Op_Body;
7416                Analyze (New_Op_Body);
7417
7418             when N_Object_Declaration =>
7419                pragma Assert (not Comes_From_Source (Op_Body));
7420                New_Op_Body := New_Copy (Op_Body);
7421                Insert_After (Current_Node, New_Op_Body);
7422                Current_Node := New_Op_Body;
7423                Analyze (New_Op_Body);
7424
7425             when others =>
7426                raise Program_Error;
7427
7428          end case;
7429
7430          Next (Op_Body);
7431       end loop;
7432
7433       --  Finally, create the body of the function that maps an entry index
7434       --  into the corresponding body index, except when there is no entry,
7435       --  or in a ravenscar-like profile.
7436
7437       if Corresponding_Runtime_Package (Pid) =
7438            System_Tasking_Protected_Objects_Entries
7439       then
7440          New_Op_Body := Build_Find_Body_Index (Pid);
7441          Insert_After (Current_Node, New_Op_Body);
7442          Current_Node := New_Op_Body;
7443          Analyze (New_Op_Body);
7444       end if;
7445
7446       --  Ada 2005 (AI-345): Construct the primitive wrapper bodies after the
7447       --  protected body. At this point all wrapper specs have been created,
7448       --  frozen and included in the dispatch table for the protected type.
7449
7450       if Ada_Version >= Ada_05 then
7451          Build_Wrapper_Bodies (Loc, Pid, Current_Node);
7452       end if;
7453    end Expand_N_Protected_Body;
7454
7455    -----------------------------------------
7456    -- Expand_N_Protected_Type_Declaration --
7457    -----------------------------------------
7458
7459    --  First we create a corresponding record type declaration used to
7460    --  represent values of this protected type.
7461    --  The general form of this type declaration is
7462
7463    --    type poV (discriminants) is record
7464    --      _Object       : aliased <kind>Protection
7465    --         [(<entry count> [, <handler count>])];
7466    --      [entry_family  : array (bounds) of Void;]
7467    --      <private data fields>
7468    --    end record;
7469
7470    --  The discriminants are present only if the corresponding protected type
7471    --  has discriminants, and they exactly mirror the protected type
7472    --  discriminants. The private data fields similarly mirror the private
7473    --  declarations of the protected type.
7474
7475    --  The Object field is always present. It contains RTS specific data used
7476    --  to control the protected object. It is declared as Aliased so that it
7477    --  can be passed as a pointer to the RTS. This allows the protected record
7478    --  to be referenced within RTS data structures. An appropriate Protection
7479    --  type and discriminant are generated.
7480
7481    --  The Service field is present for protected objects with entries. It
7482    --  contains sufficient information to allow the entry service procedure for
7483    --  this object to be called when the object is not known till runtime.
7484
7485    --  One entry_family component is present for each entry family in the
7486    --  task definition (see Expand_N_Task_Type_Declaration).
7487
7488    --  When a protected object is declared, an instance of the protected type
7489    --  value record is created. The elaboration of this declaration creates the
7490    --  correct bounds for the entry families, and also evaluates the priority
7491    --  expression if needed. The initialization routine for the protected type
7492    --  itself then calls Initialize_Protection with appropriate parameters to
7493    --  initialize the value of the Task_Id field. Install_Handlers may be also
7494    --  called if a pragma Attach_Handler applies.
7495
7496    --  Note: this record is passed to the subprograms created by the expansion
7497    --  of protected subprograms and entries. It is an in parameter to protected
7498    --  functions and an in out parameter to procedures and entry bodies. The
7499    --  Entity_Id for this created record type is placed in the
7500    --  Corresponding_Record_Type field of the associated protected type entity.
7501
7502    --  Next we create a procedure specifications for protected subprograms and
7503    --  entry bodies. For each protected subprograms two subprograms are
7504    --  created, an unprotected and a protected version. The unprotected version
7505    --  is called from within other operations of the same protected object.
7506
7507    --  We also build the call to register the procedure if a pragma
7508    --  Interrupt_Handler applies.
7509
7510    --  A single subprogram is created to service all entry bodies; it has an
7511    --  additional boolean out parameter indicating that the previous entry call
7512    --  made by the current task was serviced immediately, i.e. not by proxy.
7513    --  The O parameter contains a pointer to a record object of the type
7514    --  described above. An untyped interface is used here to allow this
7515    --  procedure to be called in places where the type of the object to be
7516    --  serviced is not known. This must be done, for example, when a call that
7517    --  may have been requeued is cancelled; the corresponding object must be
7518    --  serviced, but which object that is not known till runtime.
7519
7520    --  procedure ptypeS
7521    --    (O : System.Address; P : out Boolean);
7522    --  procedure pprocN (_object : in out poV);
7523    --  procedure pproc (_object : in out poV);
7524    --  function pfuncN (_object : poV);
7525    --  function pfunc (_object : poV);
7526    --  ...
7527
7528    --  Note that this must come after the record type declaration, since
7529    --  the specs refer to this type.
7530
7531    procedure Expand_N_Protected_Type_Declaration (N : Node_Id) is
7532       Loc      : constant Source_Ptr := Sloc (N);
7533       Prot_Typ : constant Entity_Id  := Defining_Identifier (N);
7534
7535       Pdef : constant Node_Id := Protected_Definition (N);
7536       --  This contains two lists; one for visible and one for private decls
7537
7538       Rec_Decl     : Node_Id;
7539       Cdecls       : List_Id;
7540       Discr_Map    : constant Elist_Id := New_Elmt_List;
7541       Priv         : Node_Id;
7542       New_Priv     : Node_Id;
7543       Comp         : Node_Id;
7544       Comp_Id      : Entity_Id;
7545       Sub          : Node_Id;
7546       Current_Node : Node_Id := N;
7547       Bdef         : Entity_Id := Empty; -- avoid uninit warning
7548       Edef         : Entity_Id := Empty; -- avoid uninit warning
7549       Entries_Aggr : Node_Id;
7550       Body_Id      : Entity_Id;
7551       Body_Arr     : Node_Id;
7552       E_Count      : Int;
7553       Object_Comp  : Node_Id;
7554
7555       procedure Check_Inlining (Subp : Entity_Id);
7556       --  If the original operation has a pragma Inline, propagate the flag
7557       --  to the internal body, for possible inlining later on. The source
7558       --  operation is invisible to the back-end and is never actually called.
7559
7560       function Static_Component_Size (Comp : Entity_Id) return Boolean;
7561       --  When compiling under the Ravenscar profile, private components must
7562       --  have a static size, or else a protected object  will require heap
7563       --  allocation, violating the corresponding restriction. It is preferable
7564       --  to make this check here, because it provides a better error message
7565       --  than the back-end, which refers to the object as a whole.
7566
7567       procedure Register_Handler;
7568       --  For a protected operation that is an interrupt handler, add the
7569       --  freeze action that will register it as such.
7570
7571       --------------------
7572       -- Check_Inlining --
7573       --------------------
7574
7575       procedure Check_Inlining (Subp : Entity_Id) is
7576       begin
7577          if Is_Inlined (Subp) then
7578             Set_Is_Inlined (Protected_Body_Subprogram (Subp));
7579             Set_Is_Inlined (Subp, False);
7580          end if;
7581       end Check_Inlining;
7582
7583       ---------------------------------
7584       -- Check_Static_Component_Size --
7585       ---------------------------------
7586
7587       function Static_Component_Size (Comp : Entity_Id) return Boolean is
7588          Typ : constant Entity_Id := Etype (Comp);
7589          C   : Entity_Id;
7590
7591       begin
7592          if Is_Scalar_Type (Typ) then
7593             return True;
7594
7595          elsif Is_Array_Type (Typ) then
7596             return Compile_Time_Known_Bounds (Typ);
7597
7598          elsif Is_Record_Type (Typ) then
7599             C := First_Component (Typ);
7600             while Present (C) loop
7601                if not Static_Component_Size (C) then
7602                   return False;
7603                end if;
7604
7605                Next_Component (C);
7606             end loop;
7607
7608             return True;
7609
7610          --  Any other types will be checked by the back-end
7611
7612          else
7613             return True;
7614          end if;
7615       end Static_Component_Size;
7616
7617       ----------------------
7618       -- Register_Handler --
7619       ----------------------
7620
7621       procedure Register_Handler is
7622
7623          --  All semantic checks already done in Sem_Prag
7624
7625          Prot_Proc    : constant Entity_Id :=
7626                        Defining_Unit_Name
7627                          (Specification (Current_Node));
7628
7629          Proc_Address : constant Node_Id :=
7630                           Make_Attribute_Reference (Loc,
7631                           Prefix => New_Reference_To (Prot_Proc, Loc),
7632                           Attribute_Name => Name_Address);
7633
7634          RTS_Call     : constant Entity_Id :=
7635                           Make_Procedure_Call_Statement (Loc,
7636                             Name =>
7637                               New_Reference_To (
7638                                 RTE (RE_Register_Interrupt_Handler), Loc),
7639                             Parameter_Associations =>
7640                               New_List (Proc_Address));
7641       begin
7642          Append_Freeze_Action (Prot_Proc, RTS_Call);
7643       end Register_Handler;
7644
7645    --  Start of processing for Expand_N_Protected_Type_Declaration
7646
7647    begin
7648       if Present (Corresponding_Record_Type (Prot_Typ)) then
7649          return;
7650       else
7651          Rec_Decl := Build_Corresponding_Record (N, Prot_Typ, Loc);
7652       end if;
7653
7654       Cdecls := Component_Items (Component_List (Type_Definition (Rec_Decl)));
7655
7656       --  Ada 2005 (AI-345): Propagate the attribute that contains the list
7657       --  of implemented interfaces.
7658
7659       Set_Interface_List (Type_Definition (Rec_Decl), Interface_List (N));
7660
7661       Qualify_Entity_Names (N);
7662
7663       --  If the type has discriminants, their occurrences in the declaration
7664       --  have been replaced by the corresponding discriminals. For components
7665       --  that are constrained by discriminants, their homologues in the
7666       --  corresponding record type must refer to the discriminants of that
7667       --  record, so we must apply a new renaming to subtypes_indications:
7668
7669       --     protected discriminant => discriminal => record discriminant
7670
7671       --  This replacement is not applied to default expressions, for which
7672       --  the discriminal is correct.
7673
7674       if Has_Discriminants (Prot_Typ) then
7675          declare
7676             Disc : Entity_Id;
7677             Decl : Node_Id;
7678
7679          begin
7680             Disc := First_Discriminant (Prot_Typ);
7681             Decl := First (Discriminant_Specifications (Rec_Decl));
7682             while Present (Disc) loop
7683                Append_Elmt (Discriminal (Disc), Discr_Map);
7684                Append_Elmt (Defining_Identifier (Decl), Discr_Map);
7685                Next_Discriminant (Disc);
7686                Next (Decl);
7687             end loop;
7688          end;
7689       end if;
7690
7691       --  Fill in the component declarations
7692
7693       --  Add components for entry families. For each entry family, create an
7694       --  anonymous type declaration with the same size, and analyze the type.
7695
7696       Collect_Entry_Families (Loc, Cdecls, Current_Node, Prot_Typ);
7697
7698       --  Prepend the _Object field with the right type to the component list.
7699       --  We need to compute the number of entries, and in some cases the
7700       --  number of Attach_Handler pragmas.
7701
7702       declare
7703          Ritem              : Node_Id;
7704          Num_Attach_Handler : Int := 0;
7705          Protection_Subtype : Node_Id;
7706          Entry_Count_Expr   : constant Node_Id :=
7707                                 Build_Entry_Count_Expression
7708                                   (Prot_Typ, Cdecls, Loc);
7709
7710       begin
7711          --  Could this be simplified using Corresponding_Runtime_Package???
7712
7713          if Has_Attach_Handler (Prot_Typ) then
7714             Ritem := First_Rep_Item (Prot_Typ);
7715             while Present (Ritem) loop
7716                if Nkind (Ritem) = N_Pragma
7717                  and then Pragma_Name (Ritem) = Name_Attach_Handler
7718                then
7719                   Num_Attach_Handler := Num_Attach_Handler + 1;
7720                end if;
7721
7722                Next_Rep_Item (Ritem);
7723             end loop;
7724
7725             if Restricted_Profile then
7726                if Has_Entries (Prot_Typ) then
7727                   Protection_Subtype :=
7728                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
7729                else
7730                   Protection_Subtype :=
7731                     New_Reference_To (RTE (RE_Protection), Loc);
7732                end if;
7733             else
7734                Protection_Subtype :=
7735                  Make_Subtype_Indication
7736                    (Sloc => Loc,
7737                     Subtype_Mark =>
7738                       New_Reference_To
7739                         (RTE (RE_Static_Interrupt_Protection), Loc),
7740                     Constraint =>
7741                       Make_Index_Or_Discriminant_Constraint (
7742                         Sloc => Loc,
7743                         Constraints => New_List (
7744                           Entry_Count_Expr,
7745                           Make_Integer_Literal (Loc, Num_Attach_Handler))));
7746             end if;
7747
7748          elsif Has_Interrupt_Handler (Prot_Typ) then
7749             Protection_Subtype :=
7750                Make_Subtype_Indication (
7751                  Sloc => Loc,
7752                  Subtype_Mark => New_Reference_To
7753                    (RTE (RE_Dynamic_Interrupt_Protection), Loc),
7754                  Constraint =>
7755                    Make_Index_Or_Discriminant_Constraint (
7756                      Sloc => Loc,
7757                      Constraints => New_List (Entry_Count_Expr)));
7758
7759          --  Type has explicit entries or generated primitive entry wrappers
7760
7761          elsif Has_Entries (Prot_Typ)
7762            or else (Ada_Version >= Ada_05
7763                       and then Present (Interface_List (N)))
7764          then
7765             case Corresponding_Runtime_Package (Prot_Typ) is
7766                when System_Tasking_Protected_Objects_Entries =>
7767                   Protection_Subtype :=
7768                      Make_Subtype_Indication (Loc,
7769                        Subtype_Mark =>
7770                          New_Reference_To (RTE (RE_Protection_Entries), Loc),
7771                        Constraint =>
7772                          Make_Index_Or_Discriminant_Constraint (
7773                            Sloc => Loc,
7774                            Constraints => New_List (Entry_Count_Expr)));
7775
7776                when System_Tasking_Protected_Objects_Single_Entry =>
7777                   Protection_Subtype :=
7778                     New_Reference_To (RTE (RE_Protection_Entry), Loc);
7779
7780                when others =>
7781                   raise Program_Error;
7782             end case;
7783
7784          else
7785             Protection_Subtype := New_Reference_To (RTE (RE_Protection), Loc);
7786          end if;
7787
7788          Object_Comp :=
7789            Make_Component_Declaration (Loc,
7790              Defining_Identifier =>
7791                Make_Defining_Identifier (Loc, Name_uObject),
7792              Component_Definition =>
7793                Make_Component_Definition (Loc,
7794                  Aliased_Present    => True,
7795                  Subtype_Indication => Protection_Subtype));
7796       end;
7797
7798       pragma Assert (Present (Pdef));
7799
7800       --  Add private field components
7801
7802       if Present (Private_Declarations (Pdef)) then
7803          Priv := First (Private_Declarations (Pdef));
7804
7805          while Present (Priv) loop
7806
7807             if Nkind (Priv) = N_Component_Declaration then
7808                if not Static_Component_Size (Defining_Identifier (Priv)) then
7809
7810                   --  When compiling for a restricted profile, the private
7811                   --  components must have a static size. If not, this is an
7812                   --  error for a single protected declaration, and rates a
7813                   --  warning on a protected type declaration.
7814
7815                   if not Comes_From_Source (Prot_Typ) then
7816                      Check_Restriction (No_Implicit_Heap_Allocations, Priv);
7817
7818                   elsif Restriction_Active (No_Implicit_Heap_Allocations) then
7819                      Error_Msg_N ("component has non-static size?", Priv);
7820                      Error_Msg_NE
7821                        ("\creation of protected object of type& will violate"
7822                         & " restriction No_Implicit_Heap_Allocations?",
7823                         Priv, Prot_Typ);
7824                   end if;
7825                end if;
7826
7827                --  The component definition consists of a subtype indication,
7828                --  or (in Ada 2005) an access definition. Make a copy of the
7829                --  proper definition.
7830
7831                declare
7832                   Old_Comp : constant Node_Id   := Component_Definition (Priv);
7833                   Oent     : constant Entity_Id := Defining_Identifier (Priv);
7834                   New_Comp : Node_Id;
7835                   Nent     : constant Entity_Id :=
7836                                Make_Defining_Identifier (Sloc (Oent),
7837                                  Chars => Chars (Oent));
7838
7839                begin
7840                   if Present (Subtype_Indication (Old_Comp)) then
7841                      New_Comp :=
7842                        Make_Component_Definition (Sloc (Oent),
7843                          Aliased_Present    => False,
7844                          Subtype_Indication =>
7845                            New_Copy_Tree (Subtype_Indication (Old_Comp),
7846                                            Discr_Map));
7847                   else
7848                      New_Comp :=
7849                        Make_Component_Definition (Sloc (Oent),
7850                          Aliased_Present    => False,
7851                          Access_Definition  =>
7852                            New_Copy_Tree (Access_Definition (Old_Comp),
7853                                            Discr_Map));
7854                   end if;
7855
7856                   New_Priv :=
7857                     Make_Component_Declaration (Loc,
7858                       Defining_Identifier  => Nent,
7859                       Component_Definition => New_Comp,
7860                       Expression           => Expression (Priv));
7861
7862                   Set_Has_Per_Object_Constraint (Nent,
7863                     Has_Per_Object_Constraint (Oent));
7864
7865                   Append_To (Cdecls, New_Priv);
7866                end;
7867
7868             elsif Nkind (Priv) = N_Subprogram_Declaration then
7869
7870                --  Make the unprotected version of the subprogram available
7871                --  for expansion of intra object calls. There is need for
7872                --  a protected version only if the subprogram is an interrupt
7873                --  handler, otherwise  this operation can only be called from
7874                --  within the body.
7875
7876                Sub :=
7877                  Make_Subprogram_Declaration (Loc,
7878                    Specification =>
7879                      Build_Protected_Sub_Specification
7880                        (Priv, Prot_Typ, Unprotected_Mode));
7881
7882                Insert_After (Current_Node, Sub);
7883                Analyze (Sub);
7884
7885                Set_Protected_Body_Subprogram
7886                  (Defining_Unit_Name (Specification (Priv)),
7887                   Defining_Unit_Name (Specification (Sub)));
7888                Check_Inlining (Defining_Unit_Name (Specification (Priv)));
7889                Current_Node := Sub;
7890
7891                Sub :=
7892                  Make_Subprogram_Declaration (Loc,
7893                    Specification =>
7894                      Build_Protected_Sub_Specification
7895                        (Priv, Prot_Typ, Protected_Mode));
7896
7897                Insert_After (Current_Node, Sub);
7898                Analyze (Sub);
7899                Current_Node := Sub;
7900
7901                if Is_Interrupt_Handler
7902                  (Defining_Unit_Name (Specification (Priv)))
7903                then
7904                   if not Restricted_Profile then
7905                      Register_Handler;
7906                   end if;
7907                end if;
7908             end if;
7909
7910             Next (Priv);
7911          end loop;
7912       end if;
7913
7914       --  Put the _Object component after the private component so that it
7915       --  be finalized early as required by 9.4 (20)
7916
7917       Append_To (Cdecls, Object_Comp);
7918
7919       Insert_After (Current_Node, Rec_Decl);
7920       Current_Node := Rec_Decl;
7921
7922       --  Analyze the record declaration immediately after construction,
7923       --  because the initialization procedure is needed for single object
7924       --  declarations before the next entity is analyzed (the freeze call
7925       --  that generates this initialization procedure is found below).
7926
7927       Analyze (Rec_Decl, Suppress => All_Checks);
7928
7929       --  Ada 2005 (AI-345): Construct the primitive entry wrappers before
7930       --  the corresponding record is frozen. If any wrappers are generated,
7931       --  Current_Node is updated accordingly.
7932
7933       if Ada_Version >= Ada_05 then
7934          Build_Wrapper_Specs (Loc, Prot_Typ, Current_Node);
7935       end if;
7936
7937       --  Collect pointers to entry bodies and their barriers, to be placed
7938       --  in the Entry_Bodies_Array for the type. For each entry/family we
7939       --  add an expression to the aggregate which is the initial value of
7940       --  this array. The array is declared after all protected subprograms.
7941
7942       if Has_Entries (Prot_Typ) then
7943          Entries_Aggr := Make_Aggregate (Loc, Expressions => New_List);
7944       else
7945          Entries_Aggr := Empty;
7946       end if;
7947
7948       --  Build two new procedure specifications for each protected subprogram;
7949       --  one to call from outside the object and one to call from inside.
7950       --  Build a barrier function and an entry body action procedure
7951       --  specification for each protected entry. Initialize the entry body
7952       --  array. If subprogram is flagged as eliminated, do not generate any
7953       --  internal operations.
7954
7955       E_Count := 0;
7956
7957       Comp := First (Visible_Declarations (Pdef));
7958
7959       while Present (Comp) loop
7960          if Nkind (Comp) = N_Subprogram_Declaration then
7961             Sub :=
7962               Make_Subprogram_Declaration (Loc,
7963                 Specification =>
7964                   Build_Protected_Sub_Specification
7965                     (Comp, Prot_Typ, Unprotected_Mode));
7966
7967             Insert_After (Current_Node, Sub);
7968             Analyze (Sub);
7969
7970             Set_Protected_Body_Subprogram
7971               (Defining_Unit_Name (Specification (Comp)),
7972                Defining_Unit_Name (Specification (Sub)));
7973                Check_Inlining (Defining_Unit_Name (Specification (Comp)));
7974
7975             --  Make the protected version of the subprogram available for
7976             --  expansion of external calls.
7977
7978             Current_Node := Sub;
7979
7980             Sub :=
7981               Make_Subprogram_Declaration (Loc,
7982                 Specification =>
7983                   Build_Protected_Sub_Specification
7984                     (Comp, Prot_Typ, Protected_Mode));
7985
7986             Insert_After (Current_Node, Sub);
7987             Analyze (Sub);
7988
7989             Current_Node := Sub;
7990
7991             --  Generate an overriding primitive operation specification for
7992             --  this subprogram if the protected type implements an interface.
7993
7994             if Ada_Version >= Ada_05
7995               and then
7996                 Present (Interfaces (Corresponding_Record_Type (Prot_Typ)))
7997             then
7998                Sub :=
7999                  Make_Subprogram_Declaration (Loc,
8000                    Specification =>
8001                      Build_Protected_Sub_Specification
8002                        (Comp, Prot_Typ, Dispatching_Mode));
8003
8004                Insert_After (Current_Node, Sub);
8005                Analyze (Sub);
8006
8007                Current_Node := Sub;
8008             end if;
8009
8010             --  If a pragma Interrupt_Handler applies, build and add a call to
8011             --  Register_Interrupt_Handler to the freezing actions of the
8012             --  protected version (Current_Node) of the subprogram:
8013
8014             --    system.interrupts.register_interrupt_handler
8015             --       (prot_procP'address);
8016
8017             if not Restricted_Profile
8018               and then Is_Interrupt_Handler
8019                          (Defining_Unit_Name (Specification (Comp)))
8020             then
8021                Register_Handler;
8022             end if;
8023
8024          elsif Nkind (Comp) = N_Entry_Declaration then
8025             E_Count := E_Count + 1;
8026             Comp_Id := Defining_Identifier (Comp);
8027
8028             Edef :=
8029               Make_Defining_Identifier (Loc,
8030                 Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
8031             Sub :=
8032               Make_Subprogram_Declaration (Loc,
8033                 Specification =>
8034                   Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
8035
8036             Insert_After (Current_Node, Sub);
8037             Analyze (Sub);
8038
8039             Set_Protected_Body_Subprogram
8040               (Defining_Identifier (Comp),
8041                Defining_Unit_Name (Specification (Sub)));
8042
8043             Current_Node := Sub;
8044
8045             Bdef :=
8046               Make_Defining_Identifier (Loc,
8047                 Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'B'));
8048             Sub :=
8049               Make_Subprogram_Declaration (Loc,
8050                 Specification =>
8051                   Build_Barrier_Function_Specification (Loc, Bdef));
8052
8053             Insert_After (Current_Node, Sub);
8054             Analyze (Sub);
8055             Set_Protected_Body_Subprogram (Bdef, Bdef);
8056             Set_Barrier_Function (Comp_Id, Bdef);
8057             Set_Scope (Bdef, Scope (Comp_Id));
8058             Current_Node := Sub;
8059
8060             --  Collect pointers to the protected subprogram and the barrier
8061             --  of the current entry, for insertion into Entry_Bodies_Array.
8062
8063             Append (
8064               Make_Aggregate (Loc,
8065                 Expressions => New_List (
8066                   Make_Attribute_Reference (Loc,
8067                     Prefix => New_Reference_To (Bdef, Loc),
8068                     Attribute_Name => Name_Unrestricted_Access),
8069                   Make_Attribute_Reference (Loc,
8070                     Prefix => New_Reference_To (Edef, Loc),
8071                     Attribute_Name => Name_Unrestricted_Access))),
8072               Expressions (Entries_Aggr));
8073
8074          end if;
8075
8076          Next (Comp);
8077       end loop;
8078
8079       --  If there are some private entry declarations, expand it as if they
8080       --  were visible entries.
8081
8082       if Present (Private_Declarations (Pdef)) then
8083          Comp := First (Private_Declarations (Pdef));
8084          while Present (Comp) loop
8085             if Nkind (Comp) = N_Entry_Declaration then
8086                E_Count := E_Count + 1;
8087                Comp_Id := Defining_Identifier (Comp);
8088
8089                Edef :=
8090                  Make_Defining_Identifier (Loc,
8091                   Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
8092                Sub :=
8093                  Make_Subprogram_Declaration (Loc,
8094                    Specification =>
8095                      Build_Protected_Entry_Specification (Loc, Edef, Comp_Id));
8096
8097                Insert_After (Current_Node, Sub);
8098                Analyze (Sub);
8099
8100                Set_Protected_Body_Subprogram
8101                  (Defining_Identifier (Comp),
8102                   Defining_Unit_Name (Specification (Sub)));
8103
8104                Current_Node := Sub;
8105
8106                Bdef :=
8107                  Make_Defining_Identifier (Loc,
8108                    Chars => Build_Selected_Name (Prot_Typ, Comp_Id, 'E'));
8109
8110                Sub :=
8111                  Make_Subprogram_Declaration (Loc,
8112                    Specification =>
8113                      Build_Barrier_Function_Specification (Loc, Bdef));
8114
8115                Insert_After (Current_Node, Sub);
8116                Analyze (Sub);
8117                Set_Protected_Body_Subprogram (Bdef, Bdef);
8118                Set_Barrier_Function (Comp_Id, Bdef);
8119                Set_Scope (Bdef, Scope (Comp_Id));
8120                Current_Node := Sub;
8121
8122                --  Collect pointers to the protected subprogram and the barrier
8123                --  of the current entry, for insertion into Entry_Bodies_Array.
8124
8125                Append_To (Expressions (Entries_Aggr),
8126                  Make_Aggregate (Loc,
8127                    Expressions => New_List (
8128                      Make_Attribute_Reference (Loc,
8129                        Prefix => New_Reference_To (Bdef, Loc),
8130                        Attribute_Name => Name_Unrestricted_Access),
8131                      Make_Attribute_Reference (Loc,
8132                        Prefix => New_Reference_To (Edef, Loc),
8133                        Attribute_Name => Name_Unrestricted_Access))));
8134             end if;
8135
8136             Next (Comp);
8137          end loop;
8138       end if;
8139
8140       --  Emit declaration for Entry_Bodies_Array, now that the addresses of
8141       --  all protected subprograms have been collected.
8142
8143       if Has_Entries (Prot_Typ) then
8144          Body_Id :=
8145            Make_Defining_Identifier (Sloc (Prot_Typ),
8146              Chars => New_External_Name (Chars (Prot_Typ), 'A'));
8147
8148          case Corresponding_Runtime_Package (Prot_Typ) is
8149             when System_Tasking_Protected_Objects_Entries =>
8150                Body_Arr := Make_Object_Declaration (Loc,
8151                  Defining_Identifier => Body_Id,
8152                  Aliased_Present => True,
8153                  Object_Definition =>
8154                    Make_Subtype_Indication (Loc,
8155                      Subtype_Mark => New_Reference_To (
8156                        RTE (RE_Protected_Entry_Body_Array), Loc),
8157                      Constraint =>
8158                        Make_Index_Or_Discriminant_Constraint (Loc,
8159                          Constraints => New_List (
8160                             Make_Range (Loc,
8161                               Make_Integer_Literal (Loc, 1),
8162                               Make_Integer_Literal (Loc, E_Count))))),
8163                  Expression => Entries_Aggr);
8164
8165             when System_Tasking_Protected_Objects_Single_Entry =>
8166                Body_Arr := Make_Object_Declaration (Loc,
8167                  Defining_Identifier => Body_Id,
8168                  Aliased_Present => True,
8169                  Object_Definition => New_Reference_To
8170                                         (RTE (RE_Entry_Body), Loc),
8171                  Expression =>
8172                    Make_Aggregate (Loc,
8173                      Expressions => New_List (
8174                        Make_Attribute_Reference (Loc,
8175                          Prefix => New_Reference_To (Bdef, Loc),
8176                          Attribute_Name => Name_Unrestricted_Access),
8177                        Make_Attribute_Reference (Loc,
8178                          Prefix => New_Reference_To (Edef, Loc),
8179                          Attribute_Name => Name_Unrestricted_Access))));
8180
8181             when others =>
8182                raise Program_Error;
8183          end case;
8184
8185          --  A pointer to this array will be placed in the corresponding record
8186          --  by its initialization procedure so this needs to be analyzed here.
8187
8188          Insert_After (Current_Node, Body_Arr);
8189          Current_Node := Body_Arr;
8190          Analyze (Body_Arr);
8191
8192          Set_Entry_Bodies_Array (Prot_Typ, Body_Id);
8193
8194          --  Finally, build the function that maps an entry index into the
8195          --  corresponding body. A pointer to this function is placed in each
8196          --  object of the type. Except for a ravenscar-like profile (no abort,
8197          --  no entry queue, 1 entry)
8198
8199          if Corresponding_Runtime_Package (Prot_Typ) =
8200               System_Tasking_Protected_Objects_Entries
8201          then
8202             Sub :=
8203               Make_Subprogram_Declaration (Loc,
8204                 Specification => Build_Find_Body_Index_Spec (Prot_Typ));
8205             Insert_After (Current_Node, Sub);
8206             Analyze (Sub);
8207          end if;
8208       end if;
8209    end Expand_N_Protected_Type_Declaration;
8210
8211    --------------------------------
8212    -- Expand_N_Requeue_Statement --
8213    --------------------------------
8214
8215    --  A non-dispatching requeue statement is expanded into one of four GNARLI
8216    --  operations, depending on the source and destination (task or protected
8217    --  object). A dispatching requeue statement is expanded into a call to the
8218    --  predefined primitive _Disp_Requeue. In addition, code is generated to
8219    --  jump around the remainder of processing for the original entry and, if
8220    --  the destination is (different) protected object, to attempt to service
8221    --  it. The following illustrates the various cases:
8222
8223    --  procedure entE
8224    --    (O : System.Address;
8225    --     P : System.Address;
8226    --     E : Protected_Entry_Index)
8227    --  is
8228    --     <discriminant renamings>
8229    --     <private object renamings>
8230    --     type poVP is access poV;
8231    --     _object : ptVP := ptVP!(O);
8232
8233    --  begin
8234    --     begin
8235    --        <start of statement sequence for entry>
8236
8237    --        -- Requeue from one protected entry body to another protected
8238    --        -- entry.
8239
8240    --        Requeue_Protected_Entry (
8241    --          _object._object'Access,
8242    --          new._object'Access,
8243    --          E,
8244    --          Abort_Present);
8245    --        return;
8246
8247    --        <some more of the statement sequence for entry>
8248
8249    --        --  Requeue from an entry body to a task entry
8250
8251    --        Requeue_Protected_To_Task_Entry (
8252    --          New._task_id,
8253    --          E,
8254    --          Abort_Present);
8255    --        return;
8256
8257    --        <rest of statement sequence for entry>
8258    --        Complete_Entry_Body (_object._object);
8259
8260    --     exception
8261    --        when all others =>
8262    --           Exceptional_Complete_Entry_Body (
8263    --             _object._object, Get_GNAT_Exception);
8264    --     end;
8265    --  end entE;
8266
8267    --  Requeue of a task entry call to a task entry
8268
8269    --  Accept_Call (E, Ann);
8270    --     <start of statement sequence for accept statement>
8271    --     Requeue_Task_Entry (New._task_id, E, Abort_Present);
8272    --     goto Lnn;
8273    --     <rest of statement sequence for accept statement>
8274    --     <<Lnn>>
8275    --     Complete_Rendezvous;
8276
8277    --  exception
8278    --     when all others =>
8279    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8280
8281    --  Requeue of a task entry call to a protected entry
8282
8283    --  Accept_Call (E, Ann);
8284    --     <start of statement sequence for accept statement>
8285    --     Requeue_Task_To_Protected_Entry (
8286    --       new._object'Access,
8287    --       E,
8288    --       Abort_Present);
8289    --     newS (new, Pnn);
8290    --     goto Lnn;
8291    --     <rest of statement sequence for accept statement>
8292    --     <<Lnn>>
8293    --     Complete_Rendezvous;
8294
8295    --  exception
8296    --     when all others =>
8297    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8298
8299    --  Ada 2005 (AI05-0030): Dispatching requeue from protected to interface
8300    --  class-wide type:
8301
8302    --  procedure entE
8303    --    (O : System.Address;
8304    --     P : System.Address;
8305    --     E : Protected_Entry_Index)
8306    --  is
8307    --     <discriminant renamings>
8308    --     <private object renamings>
8309    --     type poVP is access poV;
8310    --     _object : ptVP := ptVP!(O);
8311
8312    --  begin
8313    --     begin
8314    --        <start of statement sequence for entry>
8315
8316    --        _Disp_Requeue
8317    --          (<interface class-wide object>,
8318    --           True,
8319    --           _object'Address,
8320    --           Ada.Tags.Get_Offset_Index
8321    --             (Tag (_object),
8322    --              <interface dispatch table index of target entry>),
8323    --           Abort_Present);
8324    --        return;
8325
8326    --        <rest of statement sequence for entry>
8327    --        Complete_Entry_Body (_object._object);
8328
8329    --     exception
8330    --        when all others =>
8331    --           Exceptional_Complete_Entry_Body (
8332    --             _object._object, Get_GNAT_Exception);
8333    --     end;
8334    --  end entE;
8335
8336    --  Ada 2005 (AI05-0030): Dispatching requeue from task to interface
8337    --  class-wide type:
8338
8339    --  Accept_Call (E, Ann);
8340    --     <start of statement sequence for accept statement>
8341    --     _Disp_Requeue
8342    --       (<interface class-wide object>,
8343    --        False,
8344    --        null,
8345    --        Ada.Tags.Get_Offset_Index
8346    --          (Tag (_object),
8347    --           <interface dispatch table index of target entrt>),
8348    --        Abort_Present);
8349    --     newS (new, Pnn);
8350    --     goto Lnn;
8351    --     <rest of statement sequence for accept statement>
8352    --     <<Lnn>>
8353    --     Complete_Rendezvous;
8354
8355    --  exception
8356    --     when all others =>
8357    --        Exceptional_Complete_Rendezvous (Get_GNAT_Exception);
8358
8359    --  Further details on these expansions can be found in Expand_N_Protected_
8360    --  Body and Expand_N_Accept_Statement.
8361
8362    procedure Expand_N_Requeue_Statement (N : Node_Id) is
8363       Loc        : constant Source_Ptr := Sloc (N);
8364       Abortable  : Node_Id;
8365       Acc_Stat   : Node_Id;
8366       Conc_Typ   : Entity_Id;
8367       Concval    : Node_Id;
8368       Ename      : Node_Id;
8369       Index      : Node_Id;
8370       Lab_Node   : Node_Id;
8371       New_Param  : Node_Id;
8372       Old_Typ    : Entity_Id;
8373       Params     : List_Id;
8374       Rcall      : Node_Id;
8375       RTS_Call   : Entity_Id;
8376       Self_Param : Node_Id;
8377       Skip_Stat  : Node_Id;
8378
8379    begin
8380       Abortable :=
8381         New_Occurrence_Of (Boolean_Literals (Abort_Present (N)), Loc);
8382
8383       --  Extract the components of the entry call
8384
8385       Extract_Entry (N, Concval, Ename, Index);
8386       Conc_Typ := Etype (Concval);
8387
8388       --  Examine the scope stack in order to find nearest enclosing protected
8389       --  or task type. This will constitute our invocation source.
8390
8391       Old_Typ := Current_Scope;
8392       while Present (Old_Typ)
8393         and then not Is_Protected_Type (Old_Typ)
8394         and then not Is_Task_Type (Old_Typ)
8395       loop
8396          Old_Typ := Scope (Old_Typ);
8397       end loop;
8398
8399       --  Generate the parameter list for all cases. The abortable flag is
8400       --  common among dispatching and regular requeue.
8401
8402       Params := New_List (Abortable);
8403
8404       --  Ada 2005 (AI05-0030): We have a dispatching requeue of the form
8405       --  Concval.Ename where the type of Concval is class-wide concurrent
8406       --  interface.
8407
8408       if Ada_Version >= Ada_05
8409         and then Present (Concval)
8410         and then Is_Class_Wide_Type (Conc_Typ)
8411         and then Is_Concurrent_Interface (Conc_Typ)
8412       then
8413          RTS_Call := Make_Identifier (Loc, Name_uDisp_Requeue);
8414
8415          --  Generate:
8416          --    Ada.Tags.Get_Offset_Index
8417          --      (Ada.Tags.Tag (Concval),
8418          --       <interface dispatch table position of Ename>)
8419
8420          Prepend_To (Params,
8421            Make_Function_Call (Loc,
8422              Name =>
8423                New_Reference_To (RTE (RE_Get_Offset_Index), Loc),
8424              Parameter_Associations =>
8425                New_List (
8426                  Unchecked_Convert_To (RTE (RE_Tag), Concval),
8427                  Make_Integer_Literal (Loc, DT_Position (Entity (Ename))))));
8428
8429          --  Specific actuals for protected to interface class-wide type
8430          --  requeue.
8431
8432          if Is_Protected_Type (Old_Typ) then
8433             Prepend_To (Params,
8434               Make_Attribute_Reference (Loc,        --  _object'Address
8435                 Prefix =>
8436                   Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
8437                 Attribute_Name =>
8438                   Name_Address));
8439             Prepend_To (Params,                     --  True
8440               New_Reference_To (Standard_True, Loc));
8441
8442          --  Specific actuals for task to interface class-wide type requeue
8443
8444          else
8445             pragma Assert (Is_Task_Type (Old_Typ));
8446
8447             Prepend_To (Params,                     --  null
8448               New_Reference_To (RTE (RE_Null_Address), Loc));
8449             Prepend_To (Params,                     --  False
8450               New_Reference_To (Standard_False, Loc));
8451          end if;
8452
8453          --  Finally, add the common object parameter
8454
8455          Prepend_To (Params, New_Copy_Tree (Concval));
8456
8457       --  Regular requeue processing
8458
8459       else
8460          New_Param := Concurrent_Ref (Concval);
8461
8462          --  The index expression is common among all four cases
8463
8464          Prepend_To (Params,
8465            Entry_Index_Expression (Loc, Entity (Ename), Index, Conc_Typ));
8466
8467          if Is_Protected_Type (Old_Typ) then
8468             Self_Param :=
8469               Make_Attribute_Reference (Loc,
8470                 Prefix =>
8471                   Concurrent_Ref (New_Occurrence_Of (Old_Typ, Loc)),
8472                 Attribute_Name =>
8473                   Name_Unchecked_Access);
8474
8475             --  Protected to protected requeue
8476
8477             if Is_Protected_Type (Conc_Typ) then
8478                RTS_Call :=
8479                  New_Reference_To (RTE (RE_Requeue_Protected_Entry), Loc);
8480
8481                New_Param :=
8482                  Make_Attribute_Reference (Loc,
8483                    Prefix =>
8484                      New_Param,
8485                    Attribute_Name =>
8486                      Name_Unchecked_Access);
8487
8488             --  Protected to task requeue
8489
8490             else
8491                pragma Assert (Is_Task_Type (Conc_Typ));
8492                RTS_Call :=
8493                  New_Reference_To (
8494                    RTE (RE_Requeue_Protected_To_Task_Entry), Loc);
8495             end if;
8496
8497             Prepend (New_Param, Params);
8498             Prepend (Self_Param, Params);
8499
8500          else
8501             pragma Assert (Is_Task_Type (Old_Typ));
8502
8503             --  Task to protected requeue
8504
8505             if Is_Protected_Type (Conc_Typ) then
8506                RTS_Call :=
8507                  New_Reference_To (
8508                    RTE (RE_Requeue_Task_To_Protected_Entry), Loc);
8509
8510                New_Param :=
8511                  Make_Attribute_Reference (Loc,
8512                    Prefix =>
8513                      New_Param,
8514                    Attribute_Name =>
8515                      Name_Unchecked_Access);
8516
8517             --  Task to task requeue
8518
8519             else
8520                pragma Assert (Is_Task_Type (Conc_Typ));
8521                RTS_Call :=
8522                  New_Reference_To (RTE (RE_Requeue_Task_Entry), Loc);
8523             end if;
8524
8525             Prepend (New_Param, Params);
8526          end if;
8527       end if;
8528
8529       --  Create the GNARLI or predefined primitive call
8530
8531       Rcall :=
8532         Make_Procedure_Call_Statement (Loc,
8533           Name => RTS_Call,
8534           Parameter_Associations => Params);
8535
8536       Rewrite (N, Rcall);
8537       Analyze (N);
8538
8539       if Is_Protected_Type (Old_Typ) then
8540
8541          --  Build the return statement to skip the rest of the entry body
8542
8543          Skip_Stat := Make_Simple_Return_Statement (Loc);
8544
8545       else
8546          --  If the requeue is within a task, find the end label of the
8547          --  enclosing accept statement.
8548
8549          Acc_Stat := Parent (N);
8550          while Nkind (Acc_Stat) /= N_Accept_Statement loop
8551             Acc_Stat := Parent (Acc_Stat);
8552          end loop;
8553
8554          --  The last statement is the second label, used for completing the
8555          --  rendezvous the usual way. The label we are looking for is right
8556          --  before it.
8557
8558          Lab_Node :=
8559            Prev (Last (Statements (Handled_Statement_Sequence (Acc_Stat))));
8560
8561          pragma Assert (Nkind (Lab_Node) = N_Label);
8562
8563          --  Build the goto statement to skip the rest of the accept
8564          --  statement.
8565
8566          Skip_Stat :=
8567            Make_Goto_Statement (Loc,
8568              Name => New_Occurrence_Of (Entity (Identifier (Lab_Node)), Loc));
8569       end if;
8570
8571       Set_Analyzed (Skip_Stat);
8572
8573       Insert_After (N, Skip_Stat);
8574    end Expand_N_Requeue_Statement;
8575
8576    -------------------------------
8577    -- Expand_N_Selective_Accept --
8578    -------------------------------
8579
8580    procedure Expand_N_Selective_Accept (N : Node_Id) is
8581       Loc            : constant Source_Ptr := Sloc (N);
8582       Alts           : constant List_Id    := Select_Alternatives (N);
8583
8584       --  Note: in the below declarations a lot of new lists are allocated
8585       --  unconditionally which may well not end up being used. That's
8586       --  not a good idea since it wastes space gratuitously ???
8587
8588       Accept_Case    : List_Id;
8589       Accept_List    : constant List_Id := New_List;
8590
8591       Alt            : Node_Id;
8592       Alt_List       : constant List_Id := New_List;
8593       Alt_Stats      : List_Id;
8594       Ann            : Entity_Id := Empty;
8595
8596       Block          : Node_Id;
8597       Check_Guard    : Boolean := True;
8598
8599       Decls          : constant List_Id := New_List;
8600       Stats          : constant List_Id := New_List;
8601       Body_List      : constant List_Id := New_List;
8602       Trailing_List  : constant List_Id := New_List;
8603
8604       Choices        : List_Id;
8605       Else_Present   : Boolean := False;
8606       Terminate_Alt  : Node_Id := Empty;
8607       Select_Mode    : Node_Id;
8608
8609       Delay_Case     : List_Id;
8610       Delay_Count    : Integer := 0;
8611       Delay_Val      : Entity_Id;
8612       Delay_Index    : Entity_Id;
8613       Delay_Min      : Entity_Id;
8614       Delay_Num      : Int := 1;
8615       Delay_Alt_List : List_Id := New_List;
8616       Delay_List     : constant List_Id := New_List;
8617       D              : Entity_Id;
8618       M              : Entity_Id;
8619
8620       First_Delay    : Boolean := True;
8621       Guard_Open     : Entity_Id;
8622
8623       End_Lab        : Node_Id;
8624       Index          : Int := 1;
8625       Lab            : Node_Id;
8626       Num_Alts       : Int;
8627       Num_Accept     : Nat := 0;
8628       Proc           : Node_Id;
8629       Q              : Node_Id;
8630       Time_Type      : Entity_Id;
8631       X              : Node_Id;
8632       Select_Call    : Node_Id;
8633
8634       Qnam : constant Entity_Id :=
8635                Make_Defining_Identifier (Loc, New_External_Name ('S', 0));
8636
8637       Xnam : constant Entity_Id :=
8638                Make_Defining_Identifier (Loc, New_External_Name ('J', 1));
8639
8640       -----------------------
8641       -- Local subprograms --
8642       -----------------------
8643
8644       function Accept_Or_Raise return List_Id;
8645       --  For the rare case where delay alternatives all have guards, and
8646       --  all of them are closed, it is still possible that there were open
8647       --  accept alternatives with no callers. We must reexamine the
8648       --  Accept_List, and execute a selective wait with no else if some
8649       --  accept is open. If none, we raise program_error.
8650
8651       procedure Add_Accept (Alt : Node_Id);
8652       --  Process a single accept statement in a select alternative. Build
8653       --  procedure for body of accept, and add entry to dispatch table with
8654       --  expression for guard, in preparation for call to run time select.
8655
8656       function Make_And_Declare_Label (Num : Int) return Node_Id;
8657       --  Manufacture a label using Num as a serial number and declare it.
8658       --  The declaration is appended to Decls. The label marks the trailing
8659       --  statements of an accept or delay alternative.
8660
8661       function Make_Select_Call (Select_Mode : Entity_Id) return Node_Id;
8662       --  Build call to Selective_Wait runtime routine
8663
8664       procedure Process_Delay_Alternative (Alt : Node_Id; Index : Int);
8665       --  Add code to compare value of delay with previous values, and
8666       --  generate case entry for trailing statements.
8667
8668       procedure Process_Accept_Alternative
8669         (Alt   : Node_Id;
8670          Index : Int;
8671          Proc  : Node_Id);
8672       --  Add code to call corresponding procedure, and branch to
8673       --  trailing statements, if any.
8674
8675       ---------------------
8676       -- Accept_Or_Raise --
8677       ---------------------
8678
8679       function Accept_Or_Raise return List_Id is
8680          Cond  : Node_Id;
8681          Stats : List_Id;
8682          J     : constant Entity_Id := Make_Defining_Identifier (Loc,
8683                                                   New_Internal_Name ('J'));
8684
8685       begin
8686          --  We generate the following:
8687
8688          --    for J in q'range loop
8689          --       if q(J).S /=null_task_entry then
8690          --          selective_wait (simple_mode,...);
8691          --          done := True;
8692          --          exit;
8693          --       end if;
8694          --    end loop;
8695          --
8696          --    if no rendez_vous then
8697          --       raise program_error;
8698          --    end if;
8699
8700          --    Note that the code needs to know that the selector name
8701          --    in an Accept_Alternative is named S.
8702
8703          Cond := Make_Op_Ne (Loc,
8704            Left_Opnd =>
8705              Make_Selected_Component (Loc,
8706                Prefix => Make_Indexed_Component (Loc,
8707                  Prefix => New_Reference_To (Qnam, Loc),
8708                    Expressions => New_List (New_Reference_To (J, Loc))),
8709              Selector_Name => Make_Identifier (Loc, Name_S)),
8710            Right_Opnd =>
8711              New_Reference_To (RTE (RE_Null_Task_Entry), Loc));
8712
8713          Stats := New_List (
8714            Make_Implicit_Loop_Statement (N,
8715              Identifier => Empty,
8716              Iteration_Scheme =>
8717                Make_Iteration_Scheme (Loc,
8718                  Loop_Parameter_Specification =>
8719                    Make_Loop_Parameter_Specification (Loc,
8720                      Defining_Identifier => J,
8721                      Discrete_Subtype_Definition =>
8722                        Make_Attribute_Reference (Loc,
8723                          Prefix => New_Reference_To (Qnam, Loc),
8724                          Attribute_Name => Name_Range,
8725                          Expressions => New_List (
8726                            Make_Integer_Literal (Loc, 1))))),
8727
8728              Statements => New_List (
8729                Make_Implicit_If_Statement (N,
8730                  Condition =>  Cond,
8731                  Then_Statements => New_List (
8732                    Make_Select_Call (
8733                     New_Reference_To (RTE (RE_Simple_Mode), Loc)),
8734                    Make_Exit_Statement (Loc))))));
8735
8736          Append_To (Stats,
8737            Make_Raise_Program_Error (Loc,
8738              Condition => Make_Op_Eq (Loc,
8739                Left_Opnd  => New_Reference_To (Xnam, Loc),
8740                Right_Opnd =>
8741                  New_Reference_To (RTE (RE_No_Rendezvous), Loc)),
8742              Reason => PE_All_Guards_Closed));
8743
8744          return Stats;
8745       end Accept_Or_Raise;
8746
8747       ----------------
8748       -- Add_Accept --
8749       ----------------
8750
8751       procedure Add_Accept (Alt : Node_Id) is
8752          Acc_Stm   : constant Node_Id    := Accept_Statement (Alt);
8753          Ename     : constant Node_Id    := Entry_Direct_Name (Acc_Stm);
8754          Eloc      : constant Source_Ptr := Sloc (Ename);
8755          Eent      : constant Entity_Id  := Entity (Ename);
8756          Index     : constant Node_Id    := Entry_Index (Acc_Stm);
8757          Null_Body : Node_Id;
8758          Proc_Body : Node_Id;
8759          PB_Ent    : Entity_Id;
8760          Expr      : Node_Id;
8761          Call      : Node_Id;
8762
8763       begin
8764          if No (Ann) then
8765             Ann := Node (Last_Elmt (Accept_Address (Eent)));
8766          end if;
8767
8768          if Present (Condition (Alt)) then
8769             Expr :=
8770               Make_Conditional_Expression (Eloc, New_List (
8771                 Condition (Alt),
8772                 Entry_Index_Expression (Eloc, Eent, Index, Scope (Eent)),
8773                 New_Reference_To (RTE (RE_Null_Task_Entry), Eloc)));
8774          else
8775             Expr :=
8776               Entry_Index_Expression
8777                 (Eloc, Eent, Index, Scope (Eent));
8778          end if;
8779
8780          if Present (Handled_Statement_Sequence (Accept_Statement (Alt))) then
8781             Null_Body := New_Reference_To (Standard_False, Eloc);
8782
8783             if Abort_Allowed then
8784                Call := Make_Procedure_Call_Statement (Eloc,
8785                  Name => New_Reference_To (RTE (RE_Abort_Undefer), Eloc));
8786                Insert_Before (First (Statements (Handled_Statement_Sequence (
8787                  Accept_Statement (Alt)))), Call);
8788                Analyze (Call);
8789             end if;
8790
8791             PB_Ent :=
8792               Make_Defining_Identifier (Eloc,
8793                 New_External_Name (Chars (Ename), 'A', Num_Accept));
8794
8795             if Comes_From_Source (Alt) then
8796                Set_Debug_Info_Needed (PB_Ent);
8797             end if;
8798
8799             Proc_Body :=
8800               Make_Subprogram_Body (Eloc,
8801                 Specification =>
8802                   Make_Procedure_Specification (Eloc,
8803                     Defining_Unit_Name => PB_Ent),
8804                Declarations => Declarations (Acc_Stm),
8805                Handled_Statement_Sequence =>
8806                  Build_Accept_Body (Accept_Statement (Alt)));
8807
8808             --  During the analysis of the body of the accept statement, any
8809             --  zero cost exception handler records were collected in the
8810             --  Accept_Handler_Records field of the N_Accept_Alternative node.
8811             --  This is where we move them to where they belong, namely the
8812             --  newly created procedure.
8813
8814             Set_Handler_Records (PB_Ent, Accept_Handler_Records (Alt));
8815             Append (Proc_Body, Body_List);
8816
8817          else
8818             Null_Body := New_Reference_To (Standard_True,  Eloc);
8819
8820             --  if accept statement has declarations, insert above, given that
8821             --  we are not creating a body for the accept.
8822
8823             if Present (Declarations (Acc_Stm)) then
8824                Insert_Actions (N, Declarations (Acc_Stm));
8825             end if;
8826          end if;
8827
8828          Append_To (Accept_List,
8829            Make_Aggregate (Eloc, Expressions => New_List (Null_Body, Expr)));
8830
8831          Num_Accept := Num_Accept + 1;
8832       end Add_Accept;
8833
8834       ----------------------------
8835       -- Make_And_Declare_Label --
8836       ----------------------------
8837
8838       function Make_And_Declare_Label (Num : Int) return Node_Id is
8839          Lab_Id : Node_Id;
8840
8841       begin
8842          Lab_Id := Make_Identifier (Loc, New_External_Name ('L', Num));
8843          Lab :=
8844            Make_Label (Loc, Lab_Id);
8845
8846          Append_To (Decls,
8847            Make_Implicit_Label_Declaration (Loc,
8848              Defining_Identifier  =>
8849                Make_Defining_Identifier (Loc, Chars (Lab_Id)),
8850              Label_Construct => Lab));
8851
8852          return Lab;
8853       end Make_And_Declare_Label;
8854
8855       ----------------------
8856       -- Make_Select_Call --
8857       ----------------------
8858
8859       function Make_Select_Call (Select_Mode : Entity_Id) return Node_Id is
8860          Params : constant List_Id := New_List;
8861
8862       begin
8863          Append (
8864            Make_Attribute_Reference (Loc,
8865              Prefix => New_Reference_To (Qnam, Loc),
8866              Attribute_Name => Name_Unchecked_Access),
8867            Params);
8868          Append (Select_Mode, Params);
8869          Append (New_Reference_To (Ann, Loc), Params);
8870          Append (New_Reference_To (Xnam, Loc), Params);
8871
8872          return
8873            Make_Procedure_Call_Statement (Loc,
8874              Name => New_Reference_To (RTE (RE_Selective_Wait), Loc),
8875              Parameter_Associations => Params);
8876       end Make_Select_Call;
8877
8878       --------------------------------
8879       -- Process_Accept_Alternative --
8880       --------------------------------
8881
8882       procedure Process_Accept_Alternative
8883         (Alt   : Node_Id;
8884          Index : Int;
8885          Proc  : Node_Id)
8886       is
8887          Choices   : List_Id := No_List;
8888          Alt_Stats : List_Id;
8889
8890       begin
8891          Adjust_Condition (Condition (Alt));
8892          Alt_Stats := No_List;
8893
8894          if Present (Handled_Statement_Sequence (Accept_Statement (Alt))) then
8895             Choices := New_List (
8896               Make_Integer_Literal (Loc, Index));
8897
8898             Alt_Stats := New_List (
8899               Make_Procedure_Call_Statement (Sloc (Proc),
8900                 Name => New_Reference_To (
8901                   Defining_Unit_Name (Specification (Proc)), Sloc (Proc))));
8902          end if;
8903
8904          if Statements (Alt) /= Empty_List then
8905
8906             if No (Alt_Stats) then
8907
8908                --  Accept with no body, followed by trailing statements
8909
8910                Choices := New_List (
8911                  Make_Integer_Literal (Loc, Index));
8912
8913                Alt_Stats := New_List;
8914             end if;
8915
8916             --  After the call, if any, branch to trailing statements. We
8917             --  create a label for each, as well as the corresponding label
8918             --  declaration.
8919
8920             Lab := Make_And_Declare_Label (Index);
8921             Append_To (Alt_Stats,
8922               Make_Goto_Statement (Loc,
8923                 Name => New_Copy (Identifier (Lab))));
8924
8925             Append (Lab, Trailing_List);
8926             Append_List (Statements (Alt), Trailing_List);
8927             Append_To (Trailing_List,
8928               Make_Goto_Statement (Loc,
8929                 Name => New_Copy (Identifier (End_Lab))));
8930          end if;
8931
8932          if Present (Alt_Stats) then
8933
8934             --  Procedure call. and/or trailing statements
8935
8936             Append_To (Alt_List,
8937               Make_Case_Statement_Alternative (Loc,
8938                 Discrete_Choices => Choices,
8939                 Statements => Alt_Stats));
8940          end if;
8941       end Process_Accept_Alternative;
8942
8943       -------------------------------
8944       -- Process_Delay_Alternative --
8945       -------------------------------
8946
8947       procedure Process_Delay_Alternative (Alt : Node_Id; Index : Int) is
8948          Choices   : List_Id;
8949          Cond      : Node_Id;
8950          Delay_Alt : List_Id;
8951
8952       begin
8953          --  Deal with C/Fortran boolean as delay condition
8954
8955          Adjust_Condition (Condition (Alt));
8956
8957          --  Determine the smallest specified delay
8958
8959          --  for each delay alternative generate:
8960
8961          --    if guard-expression then
8962          --       Delay_Val  := delay-expression;
8963          --       Guard_Open := True;
8964          --       if Delay_Val < Delay_Min then
8965          --          Delay_Min   := Delay_Val;
8966          --          Delay_Index := Index;
8967          --       end if;
8968          --    end if;
8969
8970          --  The enclosing if-statement is omitted if there is no guard
8971
8972          if Delay_Count = 1
8973            or else First_Delay
8974          then
8975             First_Delay := False;
8976
8977             Delay_Alt := New_List (
8978               Make_Assignment_Statement (Loc,
8979                 Name => New_Reference_To (Delay_Min, Loc),
8980                 Expression => Expression (Delay_Statement (Alt))));
8981
8982             if Delay_Count > 1 then
8983                Append_To (Delay_Alt,
8984                  Make_Assignment_Statement (Loc,
8985                    Name       => New_Reference_To (Delay_Index, Loc),
8986                    Expression => Make_Integer_Literal (Loc, Index)));
8987             end if;
8988
8989          else
8990             Delay_Alt := New_List (
8991               Make_Assignment_Statement (Loc,
8992                 Name => New_Reference_To (Delay_Val, Loc),
8993                 Expression => Expression (Delay_Statement (Alt))));
8994
8995             if Time_Type = Standard_Duration then
8996                Cond :=
8997                   Make_Op_Lt (Loc,
8998                     Left_Opnd  => New_Reference_To (Delay_Val, Loc),
8999                     Right_Opnd => New_Reference_To (Delay_Min, Loc));
9000
9001             else
9002                --  The scope of the time type must define a comparison
9003                --  operator. The scope itself may not be visible, so we
9004                --  construct a node with entity information to insure that
9005                --  semantic analysis can find the proper operator.
9006
9007                Cond :=
9008                  Make_Function_Call (Loc,
9009                    Name => Make_Selected_Component (Loc,
9010                      Prefix => New_Reference_To (Scope (Time_Type), Loc),
9011                      Selector_Name =>
9012                        Make_Operator_Symbol (Loc,
9013                          Chars => Name_Op_Lt,
9014                          Strval => No_String)),
9015                     Parameter_Associations =>
9016                       New_List (
9017                         New_Reference_To (Delay_Val, Loc),
9018                         New_Reference_To (Delay_Min, Loc)));
9019
9020                Set_Entity (Prefix (Name (Cond)), Scope (Time_Type));
9021             end if;
9022
9023             Append_To (Delay_Alt,
9024               Make_Implicit_If_Statement (N,
9025                 Condition => Cond,
9026                 Then_Statements => New_List (
9027                   Make_Assignment_Statement (Loc,
9028                     Name       => New_Reference_To (Delay_Min, Loc),
9029                     Expression => New_Reference_To (Delay_Val, Loc)),
9030
9031                   Make_Assignment_Statement (Loc,
9032                     Name       => New_Reference_To (Delay_Index, Loc),
9033                     Expression => Make_Integer_Literal (Loc, Index)))));
9034          end if;
9035
9036          if Check_Guard then
9037             Append_To (Delay_Alt,
9038               Make_Assignment_Statement (Loc,
9039                 Name => New_Reference_To (Guard_Open, Loc),
9040                 Expression => New_Reference_To (Standard_True, Loc)));
9041          end if;
9042
9043          if Present (Condition (Alt)) then
9044             Delay_Alt := New_List (
9045               Make_Implicit_If_Statement (N,
9046                 Condition => Condition (Alt),
9047                 Then_Statements => Delay_Alt));
9048          end if;
9049
9050          Append_List (Delay_Alt, Delay_List);
9051
9052          --  If the delay alternative has a statement part, add choice to the
9053          --  case statements for delays.
9054
9055          if Present (Statements (Alt)) then
9056
9057             if Delay_Count = 1 then
9058                Append_List (Statements (Alt), Delay_Alt_List);
9059
9060             else
9061                Choices := New_List (
9062                  Make_Integer_Literal (Loc, Index));
9063
9064                Append_To (Delay_Alt_List,
9065                  Make_Case_Statement_Alternative (Loc,
9066                    Discrete_Choices => Choices,
9067                    Statements => Statements (Alt)));
9068             end if;
9069
9070          elsif Delay_Count = 1 then
9071
9072             --  If the single delay has no trailing statements, add a branch
9073             --  to the exit label to the selective wait.
9074
9075             Delay_Alt_List := New_List (
9076               Make_Goto_Statement (Loc,
9077                 Name => New_Copy (Identifier (End_Lab))));
9078
9079          end if;
9080       end Process_Delay_Alternative;
9081
9082    --  Start of processing for Expand_N_Selective_Accept
9083
9084    begin
9085       --  First insert some declarations before the select. The first is:
9086
9087       --    Ann : Address
9088
9089       --  This variable holds the parameters passed to the accept body. This
9090       --  declaration has already been inserted by the time we get here by
9091       --  a call to Expand_Accept_Declarations made from the semantics when
9092       --  processing the first accept statement contained in the select. We
9093       --  can find this entity as Accept_Address (E), where E is any of the
9094       --  entries references by contained accept statements.
9095
9096       --  The first step is to scan the list of Selective_Accept_Statements
9097       --  to find this entity, and also count the number of accepts, and
9098       --  determine if terminated, delay or else is present:
9099
9100       Num_Alts := 0;
9101
9102       Alt := First (Alts);
9103       while Present (Alt) loop
9104
9105          if Nkind (Alt) = N_Accept_Alternative then
9106             Add_Accept (Alt);
9107
9108          elsif Nkind (Alt) = N_Delay_Alternative then
9109             Delay_Count := Delay_Count + 1;
9110
9111             --  If the delays are relative delays, the delay expressions have
9112             --  type Standard_Duration. Otherwise they must have some time type
9113             --  recognized by GNAT.
9114
9115             if Nkind (Delay_Statement (Alt)) = N_Delay_Relative_Statement then
9116                Time_Type := Standard_Duration;
9117             else
9118                Time_Type := Etype (Expression (Delay_Statement (Alt)));
9119
9120                if Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time)
9121                  or else Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time)
9122                then
9123                   null;
9124                else
9125                   Error_Msg_NE (
9126                     "& is not a time type (RM 9.6(6))",
9127                        Expression (Delay_Statement (Alt)), Time_Type);
9128                   Time_Type := Standard_Duration;
9129                   Set_Etype (Expression (Delay_Statement (Alt)), Any_Type);
9130                end if;
9131             end if;
9132
9133             if No (Condition (Alt)) then
9134
9135                --  This guard will always be open
9136
9137                Check_Guard := False;
9138             end if;
9139
9140          elsif Nkind (Alt) = N_Terminate_Alternative then
9141             Adjust_Condition (Condition (Alt));
9142             Terminate_Alt := Alt;
9143          end if;
9144
9145          Num_Alts := Num_Alts + 1;
9146          Next (Alt);
9147       end loop;
9148
9149       Else_Present := Present (Else_Statements (N));
9150
9151       --  At the same time (see procedure Add_Accept) we build the accept list:
9152
9153       --    Qnn : Accept_List (1 .. num-select) := (
9154       --          (null-body, entry-index),
9155       --          (null-body, entry-index),
9156       --          ..
9157       --          (null_body, entry-index));
9158
9159       --  In the above declaration, null-body is True if the corresponding
9160       --  accept has no body, and false otherwise. The entry is either the
9161       --  entry index expression if there is no guard, or if a guard is
9162       --  present, then a conditional expression of the form:
9163
9164       --    (if guard then entry-index else Null_Task_Entry)
9165
9166       --  If a guard is statically known to be false, the entry can simply
9167       --  be omitted from the accept list.
9168
9169       Q :=
9170         Make_Object_Declaration (Loc,
9171           Defining_Identifier => Qnam,
9172           Object_Definition =>
9173             New_Reference_To (RTE (RE_Accept_List), Loc),
9174           Aliased_Present => True,
9175
9176           Expression =>
9177              Make_Qualified_Expression (Loc,
9178                Subtype_Mark =>
9179                  New_Reference_To (RTE (RE_Accept_List), Loc),
9180                Expression =>
9181                  Make_Aggregate (Loc, Expressions => Accept_List)));
9182
9183       Append (Q, Decls);
9184
9185       --  Then we declare the variable that holds the index for the accept
9186       --  that will be selected for service:
9187
9188       --    Xnn : Select_Index;
9189
9190       X :=
9191         Make_Object_Declaration (Loc,
9192           Defining_Identifier => Xnam,
9193           Object_Definition =>
9194             New_Reference_To (RTE (RE_Select_Index), Loc),
9195           Expression =>
9196             New_Reference_To (RTE (RE_No_Rendezvous), Loc));
9197
9198       Append (X, Decls);
9199
9200       --  After this follow procedure declarations for each accept body
9201
9202       --    procedure Pnn is
9203       --    begin
9204       --       ...
9205       --    end;
9206
9207       --  where the ... are statements from the corresponding procedure body.
9208       --  No parameters are involved, since the parameters are passed via Ann
9209       --  and the parameter references have already been expanded to be direct
9210       --  references to Ann (see Exp_Ch2.Expand_Entry_Parameter). Furthermore,
9211       --  any embedded tasking statements (which would normally be illegal in
9212       --  procedures), have been converted to calls to the tasking runtime so
9213       --  there is no problem in putting them into procedures.
9214
9215       --  The original accept statement has been expanded into a block in
9216       --  the same fashion as for simple accepts (see Build_Accept_Body).
9217
9218       --  Note: we don't really need to build these procedures for the case
9219       --  where no delay statement is present, but it is just as easy to
9220       --  build them unconditionally, and not significantly inefficient,
9221       --  since if they are short they will be inlined anyway.
9222
9223       --  The procedure declarations have been assembled in Body_List
9224
9225       --  If delays are present, we must compute the required delay.
9226       --  We first generate the declarations:
9227
9228       --    Delay_Index : Boolean := 0;
9229       --    Delay_Min   : Some_Time_Type.Time;
9230       --    Delay_Val   : Some_Time_Type.Time;
9231
9232       --  Delay_Index will be set to the index of the minimum delay, i.e. the
9233       --  active delay that is actually chosen as the basis for the possible
9234       --  delay if an immediate rendez-vous is not possible.
9235
9236       --  In the most common case there is a single delay statement, and this
9237       --  is handled specially.
9238
9239       if Delay_Count > 0 then
9240
9241          --  Generate the required declarations
9242
9243          Delay_Val :=
9244            Make_Defining_Identifier (Loc, New_External_Name ('D', 1));
9245          Delay_Index :=
9246            Make_Defining_Identifier (Loc, New_External_Name ('D', 2));
9247          Delay_Min :=
9248            Make_Defining_Identifier (Loc, New_External_Name ('D', 3));
9249
9250          Append_To (Decls,
9251            Make_Object_Declaration (Loc,
9252              Defining_Identifier => Delay_Val,
9253              Object_Definition   => New_Reference_To (Time_Type, Loc)));
9254
9255          Append_To (Decls,
9256            Make_Object_Declaration (Loc,
9257              Defining_Identifier => Delay_Index,
9258              Object_Definition   => New_Reference_To (Standard_Integer, Loc),
9259              Expression          => Make_Integer_Literal (Loc, 0)));
9260
9261          Append_To (Decls,
9262            Make_Object_Declaration (Loc,
9263              Defining_Identifier => Delay_Min,
9264              Object_Definition   => New_Reference_To (Time_Type, Loc),
9265              Expression          =>
9266                Unchecked_Convert_To (Time_Type,
9267                  Make_Attribute_Reference (Loc,
9268                    Prefix =>
9269                      New_Occurrence_Of (Underlying_Type (Time_Type), Loc),
9270                    Attribute_Name => Name_Last))));
9271
9272          --  Create Duration and Delay_Mode objects used for passing a delay
9273          --  value to RTS
9274
9275          D := Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
9276          M := Make_Defining_Identifier (Loc, New_Internal_Name ('M'));
9277
9278          declare
9279             Discr : Entity_Id;
9280
9281          begin
9282             --  Note that these values are defined in s-osprim.ads and must
9283             --  be kept in sync:
9284             --
9285             --     Relative          : constant := 0;
9286             --     Absolute_Calendar : constant := 1;
9287             --     Absolute_RT       : constant := 2;
9288
9289             if Time_Type = Standard_Duration then
9290                Discr := Make_Integer_Literal (Loc, 0);
9291
9292             elsif Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time) then
9293                Discr := Make_Integer_Literal (Loc, 1);
9294
9295             else
9296                pragma Assert
9297                  (Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time));
9298                Discr := Make_Integer_Literal (Loc, 2);
9299             end if;
9300
9301             Append_To (Decls,
9302               Make_Object_Declaration (Loc,
9303                 Defining_Identifier => D,
9304                 Object_Definition =>
9305                   New_Reference_To (Standard_Duration, Loc)));
9306
9307             Append_To (Decls,
9308               Make_Object_Declaration (Loc,
9309                 Defining_Identifier => M,
9310                 Object_Definition   =>
9311                   New_Reference_To (Standard_Integer, Loc),
9312                 Expression          => Discr));
9313          end;
9314
9315          if Check_Guard then
9316             Guard_Open :=
9317               Make_Defining_Identifier (Loc, New_External_Name ('G', 1));
9318
9319             Append_To (Decls,
9320               Make_Object_Declaration (Loc,
9321                  Defining_Identifier => Guard_Open,
9322                  Object_Definition => New_Reference_To (Standard_Boolean, Loc),
9323                  Expression        => New_Reference_To (Standard_False, Loc)));
9324          end if;
9325
9326       --  Delay_Count is zero, don't need M and D set (suppress warning)
9327
9328       else
9329          M := Empty;
9330          D := Empty;
9331       end if;
9332
9333       if Present (Terminate_Alt) then
9334
9335          --  If the terminate alternative guard is False, use
9336          --  Simple_Mode; otherwise use Terminate_Mode.
9337
9338          if Present (Condition (Terminate_Alt)) then
9339             Select_Mode := Make_Conditional_Expression (Loc,
9340               New_List (Condition (Terminate_Alt),
9341                         New_Reference_To (RTE (RE_Terminate_Mode), Loc),
9342                         New_Reference_To (RTE (RE_Simple_Mode), Loc)));
9343          else
9344             Select_Mode := New_Reference_To (RTE (RE_Terminate_Mode), Loc);
9345          end if;
9346
9347       elsif Else_Present or Delay_Count > 0 then
9348          Select_Mode := New_Reference_To (RTE (RE_Else_Mode), Loc);
9349
9350       else
9351          Select_Mode := New_Reference_To (RTE (RE_Simple_Mode), Loc);
9352       end if;
9353
9354       Select_Call := Make_Select_Call (Select_Mode);
9355       Append (Select_Call, Stats);
9356
9357       --  Now generate code to act on the result. There is an entry
9358       --  in this case for each accept statement with a non-null body,
9359       --  followed by a branch to the statements that follow the Accept.
9360       --  In the absence of delay alternatives, we generate:
9361
9362       --    case X is
9363       --      when No_Rendezvous =>  --  omitted if simple mode
9364       --         goto Lab0;
9365
9366       --      when 1 =>
9367       --         P1n;
9368       --         goto Lab1;
9369
9370       --      when 2 =>
9371       --         P2n;
9372       --         goto Lab2;
9373
9374       --      when others =>
9375       --         goto Exit;
9376       --    end case;
9377       --
9378       --    Lab0: Else_Statements;
9379       --    goto exit;
9380
9381       --    Lab1:  Trailing_Statements1;
9382       --    goto Exit;
9383       --
9384       --    Lab2:  Trailing_Statements2;
9385       --    goto Exit;
9386       --    ...
9387       --    Exit:
9388
9389       --  Generate label for common exit
9390
9391       End_Lab := Make_And_Declare_Label (Num_Alts + 1);
9392
9393       --  First entry is the default case, when no rendezvous is possible
9394
9395       Choices := New_List (New_Reference_To (RTE (RE_No_Rendezvous), Loc));
9396
9397       if Else_Present then
9398
9399          --  If no rendezvous is possible, the else part is executed
9400
9401          Lab := Make_And_Declare_Label (0);
9402          Alt_Stats := New_List (
9403            Make_Goto_Statement (Loc,
9404              Name => New_Copy (Identifier (Lab))));
9405
9406          Append (Lab, Trailing_List);
9407          Append_List (Else_Statements (N), Trailing_List);
9408          Append_To (Trailing_List,
9409            Make_Goto_Statement (Loc,
9410              Name => New_Copy (Identifier (End_Lab))));
9411       else
9412          Alt_Stats := New_List (
9413            Make_Goto_Statement (Loc,
9414              Name => New_Copy (Identifier (End_Lab))));
9415       end if;
9416
9417       Append_To (Alt_List,
9418         Make_Case_Statement_Alternative (Loc,
9419           Discrete_Choices => Choices,
9420           Statements => Alt_Stats));
9421
9422       --  We make use of the fact that Accept_Index is an integer type, and
9423       --  generate successive literals for entries for each accept. Only those
9424       --  for which there is a body or trailing statements get a case entry.
9425
9426       Alt := First (Select_Alternatives (N));
9427       Proc := First (Body_List);
9428       while Present (Alt) loop
9429
9430          if Nkind (Alt) = N_Accept_Alternative then
9431             Process_Accept_Alternative (Alt, Index, Proc);
9432             Index := Index + 1;
9433
9434             if Present
9435               (Handled_Statement_Sequence (Accept_Statement (Alt)))
9436             then
9437                Next (Proc);
9438             end if;
9439
9440          elsif Nkind (Alt) = N_Delay_Alternative then
9441             Process_Delay_Alternative (Alt, Delay_Num);
9442             Delay_Num := Delay_Num + 1;
9443          end if;
9444
9445          Next (Alt);
9446       end loop;
9447
9448       --  An others choice is always added to the main case, as well
9449       --  as the delay case (to satisfy the compiler).
9450
9451       Append_To (Alt_List,
9452         Make_Case_Statement_Alternative (Loc,
9453           Discrete_Choices =>
9454             New_List (Make_Others_Choice (Loc)),
9455           Statements       =>
9456             New_List (Make_Goto_Statement (Loc,
9457               Name => New_Copy (Identifier (End_Lab))))));
9458
9459       Accept_Case := New_List (
9460         Make_Case_Statement (Loc,
9461           Expression   => New_Reference_To (Xnam, Loc),
9462           Alternatives => Alt_List));
9463
9464       Append_List (Trailing_List, Accept_Case);
9465       Append (End_Lab, Accept_Case);
9466       Append_List (Body_List, Decls);
9467
9468       --  Construct case statement for trailing statements of delay
9469       --  alternatives, if there are several of them.
9470
9471       if Delay_Count > 1 then
9472          Append_To (Delay_Alt_List,
9473            Make_Case_Statement_Alternative (Loc,
9474              Discrete_Choices =>
9475                New_List (Make_Others_Choice (Loc)),
9476              Statements       =>
9477                New_List (Make_Null_Statement (Loc))));
9478
9479          Delay_Case := New_List (
9480            Make_Case_Statement (Loc,
9481              Expression   => New_Reference_To (Delay_Index, Loc),
9482              Alternatives => Delay_Alt_List));
9483       else
9484          Delay_Case := Delay_Alt_List;
9485       end if;
9486
9487       --  If there are no delay alternatives, we append the case statement
9488       --  to the statement list.
9489
9490       if Delay_Count = 0 then
9491          Append_List (Accept_Case, Stats);
9492
9493       --  Delay alternatives present
9494
9495       else
9496          --  If delay alternatives are present we generate:
9497
9498          --    find minimum delay.
9499          --    DX := minimum delay;
9500          --    M := <delay mode>;
9501          --    Timed_Selective_Wait (Q'Unchecked_Access, Delay_Mode, P,
9502          --      DX, MX, X);
9503          --
9504          --    if X = No_Rendezvous then
9505          --      case statement for delay statements.
9506          --    else
9507          --      case statement for accept alternatives.
9508          --    end if;
9509
9510          declare
9511             Cases : Node_Id;
9512             Stmt  : Node_Id;
9513             Parms : List_Id;
9514             Parm  : Node_Id;
9515             Conv  : Node_Id;
9516
9517          begin
9518             --  The type of the delay expression is known to be legal
9519
9520             if Time_Type = Standard_Duration then
9521                Conv := New_Reference_To (Delay_Min, Loc);
9522
9523             elsif Is_RTE (Base_Type (Etype (Time_Type)), RO_CA_Time) then
9524                Conv := Make_Function_Call (Loc,
9525                  New_Reference_To (RTE (RO_CA_To_Duration), Loc),
9526                  New_List (New_Reference_To (Delay_Min, Loc)));
9527
9528             else
9529                pragma Assert
9530                  (Is_RTE (Base_Type (Etype (Time_Type)), RO_RT_Time));
9531
9532                Conv := Make_Function_Call (Loc,
9533                  New_Reference_To (RTE (RO_RT_To_Duration), Loc),
9534                  New_List (New_Reference_To (Delay_Min, Loc)));
9535             end if;
9536
9537             Stmt := Make_Assignment_Statement (Loc,
9538               Name => New_Reference_To (D, Loc),
9539               Expression => Conv);
9540
9541             --  Change the value for Accept_Modes. (Else_Mode -> Delay_Mode)
9542
9543             Parms := Parameter_Associations (Select_Call);
9544             Parm := First (Parms);
9545
9546             while Present (Parm)
9547               and then Parm /= Select_Mode
9548             loop
9549                Next (Parm);
9550             end loop;
9551
9552             pragma Assert (Present (Parm));
9553             Rewrite (Parm, New_Reference_To (RTE (RE_Delay_Mode), Loc));
9554             Analyze (Parm);
9555
9556             --  Prepare two new parameters of Duration and Delay_Mode type
9557             --  which represent the value and the mode of the minimum delay.
9558
9559             Next (Parm);
9560             Insert_After (Parm, New_Reference_To (M, Loc));
9561             Insert_After (Parm, New_Reference_To (D, Loc));
9562
9563             --  Create a call to RTS
9564
9565             Rewrite (Select_Call,
9566               Make_Procedure_Call_Statement (Loc,
9567                 Name => New_Reference_To (RTE (RE_Timed_Selective_Wait), Loc),
9568                 Parameter_Associations => Parms));
9569
9570             --  This new call should follow the calculation of the minimum
9571             --  delay.
9572
9573             Insert_List_Before (Select_Call, Delay_List);
9574
9575             if Check_Guard then
9576                Stmt :=
9577                  Make_Implicit_If_Statement (N,
9578                    Condition => New_Reference_To (Guard_Open, Loc),
9579                    Then_Statements =>
9580                      New_List (New_Copy_Tree (Stmt),
9581                        New_Copy_Tree (Select_Call)),
9582                    Else_Statements => Accept_Or_Raise);
9583                Rewrite (Select_Call, Stmt);
9584             else
9585                Insert_Before (Select_Call, Stmt);
9586             end if;
9587
9588             Cases :=
9589               Make_Implicit_If_Statement (N,
9590                 Condition => Make_Op_Eq (Loc,
9591                   Left_Opnd  => New_Reference_To (Xnam, Loc),
9592                   Right_Opnd =>
9593                     New_Reference_To (RTE (RE_No_Rendezvous), Loc)),
9594
9595                 Then_Statements => Delay_Case,
9596                 Else_Statements => Accept_Case);
9597
9598             Append (Cases, Stats);
9599          end;
9600       end if;
9601
9602       --  Replace accept statement with appropriate block
9603
9604       Block :=
9605         Make_Block_Statement (Loc,
9606           Declarations => Decls,
9607           Handled_Statement_Sequence =>
9608             Make_Handled_Sequence_Of_Statements (Loc,
9609               Statements => Stats));
9610
9611       Rewrite (N, Block);
9612       Analyze (N);
9613
9614       --  Note: have to worry more about abort deferral in above code ???
9615
9616       --  Final step is to unstack the Accept_Address entries for all accept
9617       --  statements appearing in accept alternatives in the select statement
9618
9619       Alt := First (Alts);
9620       while Present (Alt) loop
9621          if Nkind (Alt) = N_Accept_Alternative then
9622             Remove_Last_Elmt (Accept_Address
9623               (Entity (Entry_Direct_Name (Accept_Statement (Alt)))));
9624          end if;
9625
9626          Next (Alt);
9627       end loop;
9628    end Expand_N_Selective_Accept;
9629
9630    --------------------------------------
9631    -- Expand_N_Single_Task_Declaration --
9632    --------------------------------------
9633
9634    --  Single task declarations should never be present after semantic
9635    --  analysis, since we expect them to be replaced by a declaration of an
9636    --  anonymous task type, followed by a declaration of the task object. We
9637    --  include this routine to make sure that is happening!
9638
9639    procedure Expand_N_Single_Task_Declaration (N : Node_Id) is
9640    begin
9641       raise Program_Error;
9642    end Expand_N_Single_Task_Declaration;
9643
9644    ------------------------
9645    -- Expand_N_Task_Body --
9646    ------------------------
9647
9648    --  Given a task body
9649
9650    --    task body tname is
9651    --       <declarations>
9652    --    begin
9653    --       <statements>
9654    --    end x;
9655
9656    --  This expansion routine converts it into a procedure and sets the
9657    --  elaboration flag for the procedure to true, to represent the fact
9658    --  that the task body is now elaborated:
9659
9660    --    procedure tnameB (_Task : access tnameV) is
9661    --       discriminal : dtype renames _Task.discriminant;
9662
9663    --       procedure _clean is
9664    --       begin
9665    --          Abort_Defer.all;
9666    --          Complete_Task;
9667    --          Abort_Undefer.all;
9668    --          return;
9669    --       end _clean;
9670
9671    --    begin
9672    --       Abort_Undefer.all;
9673    --       <declarations>
9674    --       System.Task_Stages.Complete_Activation;
9675    --       <statements>
9676    --    at end
9677    --       _clean;
9678    --    end tnameB;
9679
9680    --    tnameE := True;
9681
9682    --  In addition, if the task body is an activator, then a call to activate
9683    --  tasks is added at the start of the statements, before the call to
9684    --  Complete_Activation, and if in addition the task is a master then it
9685    --  must be established as a master. These calls are inserted and analyzed
9686    --  in Expand_Cleanup_Actions, when the Handled_Sequence_Of_Statements is
9687    --  expanded.
9688
9689    --  There is one discriminal declaration line generated for each
9690    --  discriminant that is present to provide an easy reference point for
9691    --  discriminant references inside the body (see Exp_Ch2.Expand_Name).
9692
9693    --  Note on relationship to GNARLI definition. In the GNARLI definition,
9694    --  task body procedures have a profile (Arg : System.Address). That is
9695    --  needed because GNARLI has to use the same access-to-subprogram type
9696    --  for all task types. We depend here on knowing that in GNAT, passing
9697    --  an address argument by value is identical to passing a record value
9698    --  by access (in either case a single pointer is passed), so even though
9699    --  this procedure has the wrong profile. In fact it's all OK, since the
9700    --  callings sequence is identical.
9701
9702    procedure Expand_N_Task_Body (N : Node_Id) is
9703       Loc   : constant Source_Ptr := Sloc (N);
9704       Ttyp  : constant Entity_Id  := Corresponding_Spec (N);
9705       Call  : Node_Id;
9706       New_N : Node_Id;
9707
9708       Insert_Nod : Node_Id;
9709       --  Used to determine the proper location of wrapper body insertions
9710
9711    begin
9712       --  Add renaming declarations for discriminals and a declaration for the
9713       --  entry family index (if applicable).
9714
9715       Install_Private_Data_Declarations
9716         (Loc, Task_Body_Procedure (Ttyp), Ttyp, N, Declarations (N));
9717
9718       --  Add a call to Abort_Undefer at the very beginning of the task
9719       --  body since this body is called with abort still deferred.
9720
9721       if Abort_Allowed then
9722          Call := Build_Runtime_Call (Loc, RE_Abort_Undefer);
9723          Insert_Before
9724            (First (Statements (Handled_Statement_Sequence (N))), Call);
9725          Analyze (Call);
9726       end if;
9727
9728       --  The statement part has already been protected with an at_end and
9729       --  cleanup actions. The call to Complete_Activation must be placed
9730       --  at the head of the sequence of statements of that block. The
9731       --  declarations have been merged in this sequence of statements but
9732       --  the first real statement is accessible from the First_Real_Statement
9733       --  field (which was set for exactly this purpose).
9734
9735       if Restricted_Profile then
9736          Call := Build_Runtime_Call (Loc, RE_Complete_Restricted_Activation);
9737       else
9738          Call := Build_Runtime_Call (Loc, RE_Complete_Activation);
9739       end if;
9740
9741       Insert_Before
9742         (First_Real_Statement (Handled_Statement_Sequence (N)), Call);
9743       Analyze (Call);
9744
9745       New_N :=
9746         Make_Subprogram_Body (Loc,
9747           Specification              => Build_Task_Proc_Specification (Ttyp),
9748           Declarations               => Declarations (N),
9749           Handled_Statement_Sequence => Handled_Statement_Sequence (N));
9750
9751       --  If the task contains generic instantiations, cleanup actions are
9752       --  delayed until after instantiation. Transfer the activation chain to
9753       --  the subprogram, to insure that the activation call is properly
9754       --  generated. It the task body contains inner tasks, indicate that the
9755       --  subprogram is a task master.
9756
9757       if Delay_Cleanups (Ttyp) then
9758          Set_Activation_Chain_Entity (New_N, Activation_Chain_Entity (N));
9759          Set_Is_Task_Master  (New_N, Is_Task_Master (N));
9760       end if;
9761
9762       Rewrite (N, New_N);
9763       Analyze (N);
9764
9765       --  Set elaboration flag immediately after task body. If the body is a
9766       --  subunit, the flag is set in the declarative part containing the stub.
9767
9768       if Nkind (Parent (N)) /= N_Subunit then
9769          Insert_After (N,
9770            Make_Assignment_Statement (Loc,
9771              Name =>
9772                Make_Identifier (Loc, New_External_Name (Chars (Ttyp), 'E')),
9773              Expression => New_Reference_To (Standard_True, Loc)));
9774       end if;
9775
9776       --  Ada 2005 (AI-345): Construct the primitive entry wrapper bodies after
9777       --  the task body. At this point all wrapper specs have been created,
9778       --  frozen and included in the dispatch table for the task type.
9779
9780       if Ada_Version >= Ada_05 then
9781          if Nkind (Parent (N)) = N_Subunit then
9782             Insert_Nod := Corresponding_Stub (Parent (N));
9783          else
9784             Insert_Nod := N;
9785          end if;
9786
9787          Build_Wrapper_Bodies (Loc, Ttyp, Insert_Nod);
9788       end if;
9789    end Expand_N_Task_Body;
9790
9791    ------------------------------------
9792    -- Expand_N_Task_Type_Declaration --
9793    ------------------------------------
9794
9795    --  We have several things to do. First we must create a Boolean flag used
9796    --  to mark if the body is elaborated yet. This variable gets set to True
9797    --  when the body of the task is elaborated (we can't rely on the normal
9798    --  ABE mechanism for the task body, since we need to pass an access to
9799    --  this elaboration boolean to the runtime routines).
9800
9801    --    taskE : aliased Boolean := False;
9802
9803    --  Next a variable is declared to hold the task stack size (either the
9804    --  default : Unspecified_Size, or a value that is set by a pragma
9805    --  Storage_Size). If the value of the pragma Storage_Size is static, then
9806    --  the variable is initialized with this value:
9807
9808    --    taskZ : Size_Type := Unspecified_Size;
9809    --  or
9810    --    taskZ : Size_Type := Size_Type (size_expression);
9811
9812    --  Note: No variable is needed to hold the task relative deadline since
9813    --  its value would never be static because the parameter is of a private
9814    --  type (Ada.Real_Time.Time_Span).
9815
9816    --  Next we create a corresponding record type declaration used to represent
9817    --  values of this task. The general form of this type declaration is
9818
9819    --    type taskV (discriminants) is record
9820    --      _Task_Id     : Task_Id;
9821    --      entry_family : array (bounds) of Void;
9822    --      _Priority    : Integer         := priority_expression;
9823    --      _Size        : Size_Type       := Size_Type (size_expression);
9824    --      _Task_Info   : Task_Info_Type  := task_info_expression;
9825    --    end record;
9826
9827    --  The discriminants are present only if the corresponding task type has
9828    --  discriminants, and they exactly mirror the task type discriminants.
9829
9830    --  The Id field is always present. It contains the Task_Id value, as set by
9831    --  the call to Create_Task. Note that although the task is limited, the
9832    --  task value record type is not limited, so there is no problem in passing
9833    --  this field as an out parameter to Create_Task.
9834
9835    --  One entry_family component is present for each entry family in the task
9836    --  definition. The bounds correspond to the bounds of the entry family
9837    --  (which may depend on discriminants). The element type is void, since we
9838    --  only need the bounds information for determining the entry index. Note
9839    --  that the use of an anonymous array would normally be illegal in this
9840    --  context, but this is a parser check, and the semantics is quite prepared
9841    --  to handle such a case.
9842
9843    --  The _Size field is present only if a Storage_Size pragma appears in the
9844    --  task definition. The expression captures the argument that was present
9845    --  in the pragma, and is used to override the task stack size otherwise
9846    --  associated with the task type.
9847
9848    --  The _Priority field is present only if a Priority or Interrupt_Priority
9849    --  pragma appears in the task definition. The expression captures the
9850    --  argument that was present in the pragma, and is used to provide the Size
9851    --  parameter to the call to Create_Task.
9852
9853    --  The _Task_Info field is present only if a Task_Info pragma appears in
9854    --  the task definition. The expression captures the argument that was
9855    --  present in the pragma, and is used to provide the Task_Image parameter
9856    --  to the call to Create_Task.
9857
9858    --  The _Relative_Deadline field is present only if a Relative_Deadline
9859    --  pragma appears in the task definition. The expression captures the
9860    --  argument that was present in the pragma, and is used to provide the
9861    --  Relative_Deadline parameter to the call to Create_Task.
9862
9863    --  When a task is declared, an instance of the task value record is
9864    --  created. The elaboration of this declaration creates the correct bounds
9865    --  for the entry families, and also evaluates the size, priority, and
9866    --  task_Info expressions if needed. The initialization routine for the task
9867    --  type itself then calls Create_Task with appropriate parameters to
9868    --  initialize the value of the Task_Id field.
9869
9870    --  Note: the address of this record is passed as the "Discriminants"
9871    --  parameter for Create_Task. Since Create_Task merely passes this onto the
9872    --  body procedure, it does not matter that it does not quite match the
9873    --  GNARLI model of what is being passed (the record contains more than just
9874    --  the discriminants, but the discriminants can be found from the record
9875    --  value).
9876
9877    --  The Entity_Id for this created record type is placed in the
9878    --  Corresponding_Record_Type field of the associated task type entity.
9879
9880    --  Next we create a procedure specification for the task body procedure:
9881
9882    --    procedure taskB (_Task : access taskV);
9883
9884    --  Note that this must come after the record type declaration, since
9885    --  the spec refers to this type. It turns out that the initialization
9886    --  procedure for the value type references the task body spec, but that's
9887    --  fine, since it won't be generated till the freeze point for the type,
9888    --  which is certainly after the task body spec declaration.
9889
9890    --  Finally, we set the task index value field of the entry attribute in
9891    --  the case of a simple entry.
9892
9893    procedure Expand_N_Task_Type_Declaration (N : Node_Id) is
9894       Loc     : constant Source_Ptr := Sloc (N);
9895       Tasktyp : constant Entity_Id  := Etype (Defining_Identifier (N));
9896       Tasknm  : constant Name_Id    := Chars (Tasktyp);
9897       Taskdef : constant Node_Id    := Task_Definition (N);
9898
9899       Proc_Spec  : Node_Id;
9900       Rec_Decl   : Node_Id;
9901       Rec_Ent    : Entity_Id;
9902       Cdecls     : List_Id;
9903       Elab_Decl  : Node_Id;
9904       Size_Decl  : Node_Id;
9905       Body_Decl  : Node_Id;
9906       Task_Size  : Node_Id;
9907       Ent_Stack  : Entity_Id;
9908       Decl_Stack : Node_Id;
9909
9910    begin
9911       --  If already expanded, nothing to do
9912
9913       if Present (Corresponding_Record_Type (Tasktyp)) then
9914          return;
9915       end if;
9916
9917       --  Here we will do the expansion
9918
9919       Rec_Decl := Build_Corresponding_Record (N, Tasktyp, Loc);
9920
9921       --  Ada 2005 (AI-345): Propagate the attribute that contains the list
9922       --  of implemented interfaces.
9923
9924       Set_Interface_List (Type_Definition (Rec_Decl), Interface_List (N));
9925
9926       Rec_Ent  := Defining_Identifier (Rec_Decl);
9927       Cdecls   := Component_Items (Component_List
9928                                      (Type_Definition (Rec_Decl)));
9929
9930       Qualify_Entity_Names (N);
9931
9932       --  First create the elaboration variable
9933
9934       Elab_Decl :=
9935         Make_Object_Declaration (Loc,
9936           Defining_Identifier =>
9937             Make_Defining_Identifier (Sloc (Tasktyp),
9938               Chars => New_External_Name (Tasknm, 'E')),
9939           Aliased_Present      => True,
9940           Object_Definition    => New_Reference_To (Standard_Boolean, Loc),
9941           Expression           => New_Reference_To (Standard_False, Loc));
9942       Insert_After (N, Elab_Decl);
9943
9944       --  Next create the declaration of the size variable (tasknmZ)
9945
9946       Set_Storage_Size_Variable (Tasktyp,
9947         Make_Defining_Identifier (Sloc (Tasktyp),
9948           Chars => New_External_Name (Tasknm, 'Z')));
9949
9950       if Present (Taskdef) and then Has_Storage_Size_Pragma (Taskdef) and then
9951         Is_Static_Expression (Expression (First (
9952           Pragma_Argument_Associations (Find_Task_Or_Protected_Pragma (
9953             Taskdef, Name_Storage_Size)))))
9954       then
9955          Size_Decl :=
9956            Make_Object_Declaration (Loc,
9957              Defining_Identifier => Storage_Size_Variable (Tasktyp),
9958              Object_Definition => New_Reference_To (RTE (RE_Size_Type), Loc),
9959              Expression =>
9960                Convert_To (RTE (RE_Size_Type),
9961                  Relocate_Node (
9962                    Expression (First (
9963                      Pragma_Argument_Associations (
9964                        Find_Task_Or_Protected_Pragma
9965                          (Taskdef, Name_Storage_Size)))))));
9966
9967       else
9968          Size_Decl :=
9969            Make_Object_Declaration (Loc,
9970              Defining_Identifier => Storage_Size_Variable (Tasktyp),
9971              Object_Definition => New_Reference_To (RTE (RE_Size_Type), Loc),
9972              Expression => New_Reference_To (RTE (RE_Unspecified_Size), Loc));
9973       end if;
9974
9975       Insert_After (Elab_Decl, Size_Decl);
9976
9977       --  Next build the rest of the corresponding record declaration. This is
9978       --  done last, since the corresponding record initialization procedure
9979       --  will reference the previously created entities.
9980
9981       --  Fill in the component declarations -- first the _Task_Id field
9982
9983       Append_To (Cdecls,
9984         Make_Component_Declaration (Loc,
9985           Defining_Identifier =>
9986             Make_Defining_Identifier (Loc, Name_uTask_Id),
9987           Component_Definition =>
9988             Make_Component_Definition (Loc,
9989               Aliased_Present    => False,
9990               Subtype_Indication => New_Reference_To (RTE (RO_ST_Task_Id),
9991                                     Loc))));
9992
9993       --  Declare static ATCB (that is, created by the expander) if we are
9994       --  using the Restricted run time.
9995
9996       if Restricted_Profile then
9997          Append_To (Cdecls,
9998            Make_Component_Declaration (Loc,
9999              Defining_Identifier  =>
10000                Make_Defining_Identifier (Loc, Name_uATCB),
10001
10002              Component_Definition =>
10003                Make_Component_Definition (Loc,
10004                  Aliased_Present     => True,
10005                  Subtype_Indication  => Make_Subtype_Indication (Loc,
10006                    Subtype_Mark => New_Occurrence_Of
10007                      (RTE (RE_Ada_Task_Control_Block), Loc),
10008
10009                    Constraint   =>
10010                      Make_Index_Or_Discriminant_Constraint (Loc,
10011                        Constraints =>
10012                          New_List (Make_Integer_Literal (Loc, 0)))))));
10013
10014       end if;
10015
10016       --  Declare static stack (that is, created by the expander) if we are
10017       --  using the Restricted run time on a bare board configuration.
10018
10019       if Restricted_Profile
10020         and then Preallocated_Stacks_On_Target
10021       then
10022          --  First we need to extract the appropriate stack size
10023
10024          Ent_Stack := Make_Defining_Identifier (Loc, Name_uStack);
10025
10026          if Present (Taskdef) and then Has_Storage_Size_Pragma (Taskdef) then
10027             declare
10028                Expr_N : constant Node_Id :=
10029                           Expression (First (
10030                             Pragma_Argument_Associations (
10031                               Find_Task_Or_Protected_Pragma
10032                                 (Taskdef, Name_Storage_Size))));
10033                Etyp   : constant Entity_Id := Etype (Expr_N);
10034                P      : constant Node_Id   := Parent (Expr_N);
10035
10036             begin
10037                --  The stack is defined inside the corresponding record.
10038                --  Therefore if the size of the stack is set by means of
10039                --  a discriminant, we must reference the discriminant of the
10040                --  corresponding record type.
10041
10042                if Nkind (Expr_N) in N_Has_Entity
10043                  and then Present (Discriminal_Link (Entity (Expr_N)))
10044                then
10045                   Task_Size :=
10046                     New_Reference_To
10047                       (CR_Discriminant (Discriminal_Link (Entity (Expr_N))),
10048                        Loc);
10049                   Set_Parent   (Task_Size, P);
10050                   Set_Etype    (Task_Size, Etyp);
10051                   Set_Analyzed (Task_Size);
10052
10053                else
10054                   Task_Size := Relocate_Node (Expr_N);
10055                end if;
10056             end;
10057
10058          else
10059             Task_Size :=
10060               New_Reference_To (RTE (RE_Default_Stack_Size), Loc);
10061          end if;
10062
10063          Decl_Stack := Make_Component_Declaration (Loc,
10064            Defining_Identifier  => Ent_Stack,
10065
10066            Component_Definition =>
10067              Make_Component_Definition (Loc,
10068                Aliased_Present     => True,
10069                Subtype_Indication  => Make_Subtype_Indication (Loc,
10070                  Subtype_Mark =>
10071                    New_Occurrence_Of (RTE (RE_Storage_Array), Loc),
10072
10073                  Constraint   =>
10074                    Make_Index_Or_Discriminant_Constraint (Loc,
10075                      Constraints  => New_List (Make_Range (Loc,
10076                        Low_Bound  => Make_Integer_Literal (Loc, 1),
10077                        High_Bound => Convert_To (RTE (RE_Storage_Offset),
10078                          Task_Size)))))));
10079
10080          Append_To (Cdecls, Decl_Stack);
10081
10082          --  The appropriate alignment for the stack is ensured by the run-time
10083          --  code in charge of task creation.
10084
10085       end if;
10086
10087       --  Add components for entry families
10088
10089       Collect_Entry_Families (Loc, Cdecls, Size_Decl, Tasktyp);
10090
10091       --  Add the _Priority component if a Priority pragma is present
10092
10093       if Present (Taskdef) and then Has_Priority_Pragma (Taskdef) then
10094          declare
10095             Prag : constant Node_Id :=
10096                      Find_Task_Or_Protected_Pragma (Taskdef, Name_Priority);
10097             Expr : Node_Id;
10098
10099          begin
10100             Expr := First (Pragma_Argument_Associations (Prag));
10101
10102             if Nkind (Expr) = N_Pragma_Argument_Association then
10103                Expr := Expression (Expr);
10104             end if;
10105
10106             Expr := New_Copy_Tree (Expr);
10107
10108             --  Add conversion to proper type to do range check if required
10109             --  Note that for runtime units, we allow out of range interrupt
10110             --  priority values to be used in a priority pragma. This is for
10111             --  the benefit of some versions of System.Interrupts which use
10112             --  a special server task with maximum interrupt priority.
10113
10114             if Pragma_Name (Prag) = Name_Priority
10115               and then not GNAT_Mode
10116             then
10117                Rewrite (Expr, Convert_To (RTE (RE_Priority), Expr));
10118             else
10119                Rewrite (Expr, Convert_To (RTE (RE_Any_Priority), Expr));
10120             end if;
10121
10122             Append_To (Cdecls,
10123               Make_Component_Declaration (Loc,
10124                 Defining_Identifier =>
10125                   Make_Defining_Identifier (Loc, Name_uPriority),
10126                 Component_Definition =>
10127                   Make_Component_Definition (Loc,
10128                     Aliased_Present    => False,
10129                     Subtype_Indication => New_Reference_To (Standard_Integer,
10130                                                             Loc)),
10131                 Expression => Expr));
10132          end;
10133       end if;
10134
10135       --  Add the _Task_Size component if a Storage_Size pragma is present
10136
10137       if Present (Taskdef)
10138         and then Has_Storage_Size_Pragma (Taskdef)
10139       then
10140          Append_To (Cdecls,
10141            Make_Component_Declaration (Loc,
10142              Defining_Identifier =>
10143                Make_Defining_Identifier (Loc, Name_uSize),
10144
10145              Component_Definition =>
10146                Make_Component_Definition (Loc,
10147                  Aliased_Present    => False,
10148                  Subtype_Indication => New_Reference_To (RTE (RE_Size_Type),
10149                                                          Loc)),
10150
10151              Expression =>
10152                Convert_To (RTE (RE_Size_Type),
10153                  Relocate_Node (
10154                    Expression (First (
10155                      Pragma_Argument_Associations (
10156                        Find_Task_Or_Protected_Pragma
10157                          (Taskdef, Name_Storage_Size))))))));
10158       end if;
10159
10160       --  Add the _Task_Info component if a Task_Info pragma is present
10161
10162       if Present (Taskdef) and then Has_Task_Info_Pragma (Taskdef) then
10163          Append_To (Cdecls,
10164            Make_Component_Declaration (Loc,
10165              Defining_Identifier =>
10166                Make_Defining_Identifier (Loc, Name_uTask_Info),
10167
10168              Component_Definition =>
10169                Make_Component_Definition (Loc,
10170                  Aliased_Present    => False,
10171                  Subtype_Indication =>
10172                    New_Reference_To (RTE (RE_Task_Info_Type), Loc)),
10173
10174              Expression => New_Copy (
10175                Expression (First (
10176                  Pragma_Argument_Associations (
10177                    Find_Task_Or_Protected_Pragma
10178                      (Taskdef, Name_Task_Info)))))));
10179       end if;
10180
10181       --  Add the _Relative_Deadline component if a Relative_Deadline pragma is
10182       --  present. If we are using a restricted run time this component will
10183       --  not be added (deadlines are not allowed by the Ravenscar profile).
10184
10185       if not Restricted_Profile
10186         and then Present (Taskdef)
10187         and then Has_Relative_Deadline_Pragma (Taskdef)
10188       then
10189          Append_To (Cdecls,
10190            Make_Component_Declaration (Loc,
10191              Defining_Identifier =>
10192                Make_Defining_Identifier (Loc, Name_uRelative_Deadline),
10193
10194              Component_Definition =>
10195                Make_Component_Definition (Loc,
10196                  Aliased_Present    => False,
10197                  Subtype_Indication =>
10198                    New_Reference_To (RTE (RE_Time_Span), Loc)),
10199
10200              Expression =>
10201                Convert_To (RTE (RE_Time_Span),
10202                  Relocate_Node (
10203                    Expression (First (
10204                      Pragma_Argument_Associations (
10205                        Find_Task_Or_Protected_Pragma
10206                          (Taskdef, Name_Relative_Deadline))))))));
10207       end if;
10208
10209       Insert_After (Size_Decl, Rec_Decl);
10210
10211       --  Analyze the record declaration immediately after construction,
10212       --  because the initialization procedure is needed for single task
10213       --  declarations before the next entity is analyzed.
10214
10215       Analyze (Rec_Decl);
10216
10217       --  Create the declaration of the task body procedure
10218
10219       Proc_Spec := Build_Task_Proc_Specification (Tasktyp);
10220       Body_Decl :=
10221         Make_Subprogram_Declaration (Loc,
10222           Specification => Proc_Spec);
10223
10224       Insert_After (Rec_Decl, Body_Decl);
10225
10226       --  The subprogram does not comes from source, so we have to indicate the
10227       --  need for debugging information explicitly.
10228
10229       if Comes_From_Source (Original_Node (N)) then
10230          Set_Debug_Info_Needed (Defining_Entity (Proc_Spec));
10231       end if;
10232
10233       --  Ada 2005 (AI-345): Construct the primitive entry wrapper specs before
10234       --  the corresponding record has been frozen.
10235
10236       if Ada_Version >= Ada_05 then
10237          Build_Wrapper_Specs (Loc, Tasktyp, Rec_Decl);
10238       end if;
10239
10240       --  Ada 2005 (AI-345): We must defer freezing to allow further
10241       --  declaration of primitive subprograms covering task interfaces
10242
10243       if Ada_Version <= Ada_95 then
10244
10245          --  Now we can freeze the corresponding record. This needs manually
10246          --  freezing, since it is really part of the task type, and the task
10247          --  type is frozen at this stage. We of course need the initialization
10248          --  procedure for this corresponding record type and we won't get it
10249          --  in time if we don't freeze now.
10250
10251          declare
10252             L : constant List_Id := Freeze_Entity (Rec_Ent, Loc);
10253          begin
10254             if Is_Non_Empty_List (L) then
10255                Insert_List_After (Body_Decl, L);
10256             end if;
10257          end;
10258       end if;
10259
10260       --  Complete the expansion of access types to the current task type, if
10261       --  any were declared.
10262
10263       Expand_Previous_Access_Type (Tasktyp);
10264    end Expand_N_Task_Type_Declaration;
10265
10266    -------------------------------
10267    -- Expand_N_Timed_Entry_Call --
10268    -------------------------------
10269
10270    --  A timed entry call in normal case is not implemented using ATC mechanism
10271    --  anymore for efficiency reason.
10272
10273    --     select
10274    --        T.E;
10275    --        S1;
10276    --     or
10277    --        Delay D;
10278    --        S2;
10279    --     end select;
10280
10281    --  is expanded as follow:
10282
10283    --  1) When T.E is a task entry_call;
10284
10285    --    declare
10286    --       B  : Boolean;
10287    --       X  : Task_Entry_Index := <entry index>;
10288    --       DX : Duration := To_Duration (D);
10289    --       M  : Delay_Mode := <discriminant>;
10290    --       P  : parms := (parm, parm, parm);
10291
10292    --    begin
10293    --       Timed_Protected_Entry_Call
10294    --         (<acceptor-task>, X, P'Address, DX, M, B);
10295    --       if B then
10296    --          S1;
10297    --       else
10298    --          S2;
10299    --       end if;
10300    --    end;
10301
10302    --  2) When T.E is a protected entry_call;
10303
10304    --    declare
10305    --       B  : Boolean;
10306    --       X  : Protected_Entry_Index := <entry index>;
10307    --       DX : Duration := To_Duration (D);
10308    --       M  : Delay_Mode := <discriminant>;
10309    --       P  : parms := (parm, parm, parm);
10310
10311    --    begin
10312    --       Timed_Protected_Entry_Call
10313    --         (<object>'unchecked_access, X, P'Address, DX, M, B);
10314    --       if B then
10315    --          S1;
10316    --       else
10317    --          S2;
10318    --       end if;
10319    --    end;
10320
10321    --  3) Ada 2005 (AI-345): When T.E is a dispatching procedure call;
10322
10323    --    declare
10324    --       B  : Boolean := False;
10325    --       C  : Ada.Tags.Prim_Op_Kind;
10326    --       DX : Duration := To_Duration (D)
10327    --       K  : Ada.Tags.Tagged_Kind :=
10328    --              Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag (<object>));
10329    --       M  : Integer :=...;
10330    --       P  : Parameters := (Param1 .. ParamN);
10331    --       S  : Iteger;
10332
10333    --    begin
10334    --       if K = Ada.Tags.TK_Limited_Tagged then
10335    --          <dispatching-call>;
10336    --          <triggering-statements>
10337
10338    --       else
10339    --          S :=
10340    --            Ada.Tags.Get_Offset_Index
10341    --              (Ada.Tags.Tag (<object>), DT_Position (<dispatching-call>));
10342
10343    --          _Disp_Timed_Select (<object>, S, P'Address, DX, M, C, B);
10344
10345    --          if C = POK_Protected_Entry
10346    --            or else C = POK_Task_Entry
10347    --          then
10348    --             Param1 := P.Param1;
10349    --             ...
10350    --             ParamN := P.ParamN;
10351    --          end if;
10352
10353    --          if B then
10354    --             if C = POK_Procedure
10355    --               or else C = POK_Protected_Procedure
10356    --               or else C = POK_Task_Procedure
10357    --             then
10358    --                <dispatching-call>;
10359    --             end if;
10360
10361    --             <triggering-statements>
10362    --          else
10363    --             <timed-statements>
10364    --          end if;
10365    --       end if;
10366    --    end;
10367
10368    procedure Expand_N_Timed_Entry_Call (N : Node_Id) is
10369       Loc : constant Source_Ptr := Sloc (N);
10370
10371       E_Call  : Node_Id :=
10372                   Entry_Call_Statement (Entry_Call_Alternative (N));
10373       E_Stats : constant List_Id :=
10374                   Statements (Entry_Call_Alternative (N));
10375       D_Stat  : Node_Id :=
10376                   Delay_Statement (Delay_Alternative (N));
10377       D_Stats : constant List_Id :=
10378                   Statements (Delay_Alternative (N));
10379
10380       Actuals        : List_Id;
10381       Blk_Typ        : Entity_Id;
10382       Call           : Node_Id;
10383       Call_Ent       : Entity_Id;
10384       Conc_Typ_Stmts : List_Id;
10385       Concval        : Node_Id;
10386       D_Conv         : Node_Id;
10387       D_Disc         : Node_Id;
10388       D_Type         : Entity_Id;
10389       Decls          : List_Id;
10390       Dummy          : Node_Id;
10391       Ename          : Node_Id;
10392       Formals        : List_Id;
10393       Index          : Node_Id;
10394       Is_Disp_Select : Boolean;
10395       Lim_Typ_Stmts  : List_Id;
10396       N_Stats        : List_Id;
10397       Obj            : Entity_Id;
10398       Param          : Node_Id;
10399       Params         : List_Id;
10400       Stmt           : Node_Id;
10401       Stmts          : List_Id;
10402       Unpack         : List_Id;
10403
10404       B : Entity_Id;  --  Call status flag
10405       C : Entity_Id;  --  Call kind
10406       D : Entity_Id;  --  Delay
10407       K : Entity_Id;  --  Tagged kind
10408       M : Entity_Id;  --  Delay mode
10409       P : Entity_Id;  --  Parameter block
10410       S : Entity_Id;  --  Primitive operation slot
10411
10412    begin
10413       --  Under the Ravenscar profile, timed entry calls are excluded. An error
10414       --  was already reported on spec, so do not attempt to expand the call.
10415
10416       if Restriction_Active (No_Select_Statements) then
10417          return;
10418       end if;
10419
10420       --  The arguments in the call may require dynamic allocation, and the
10421       --  call statement may have been transformed into a block. The block
10422       --  may contain additional declarations for internal entities, and the
10423       --  original call is found by sequential search.
10424
10425       if Nkind (E_Call) = N_Block_Statement then
10426          E_Call := First (Statements (Handled_Statement_Sequence (E_Call)));
10427          while not Nkind_In (E_Call, N_Procedure_Call_Statement,
10428                                      N_Entry_Call_Statement)
10429          loop
10430             Next (E_Call);
10431          end loop;
10432       end if;
10433
10434       Is_Disp_Select :=
10435         Ada_Version >= Ada_05
10436           and then Nkind (E_Call) = N_Procedure_Call_Statement;
10437
10438       if Is_Disp_Select then
10439          Extract_Dispatching_Call (E_Call, Call_Ent, Obj, Actuals, Formals);
10440
10441          Decls := New_List;
10442          Stmts := New_List;
10443
10444          --  Generate:
10445          --    B : Boolean := False;
10446
10447          B := Build_B (Loc, Decls);
10448
10449          --  Generate:
10450          --    C : Ada.Tags.Prim_Op_Kind;
10451
10452          C := Build_C (Loc, Decls);
10453
10454          --  Because the analysis of all statements was disabled, manually
10455          --  analyze the delay statement.
10456
10457          Analyze (D_Stat);
10458          D_Stat := Original_Node (D_Stat);
10459
10460       else
10461          --  Build an entry call using Simple_Entry_Call
10462
10463          Extract_Entry (E_Call, Concval, Ename, Index);
10464          Build_Simple_Entry_Call (E_Call, Concval, Ename, Index);
10465
10466          Decls := Declarations (E_Call);
10467          Stmts := Statements (Handled_Statement_Sequence (E_Call));
10468
10469          if No (Decls) then
10470             Decls := New_List;
10471          end if;
10472
10473          --  Generate:
10474          --    B : Boolean;
10475
10476          B := Make_Defining_Identifier (Loc, Name_uB);
10477
10478          Prepend_To (Decls,
10479            Make_Object_Declaration (Loc,
10480              Defining_Identifier =>
10481                B,
10482              Object_Definition =>
10483                New_Reference_To (Standard_Boolean, Loc)));
10484       end if;
10485
10486       --  Duration and mode processing
10487
10488       D_Type := Base_Type (Etype (Expression (D_Stat)));
10489
10490       --  Use the type of the delay expression (Calendar or Real_Time) to
10491       --  generate the appropriate conversion.
10492
10493       if Nkind (D_Stat) = N_Delay_Relative_Statement then
10494          D_Disc := Make_Integer_Literal (Loc, 0);
10495          D_Conv := Relocate_Node (Expression (D_Stat));
10496
10497       elsif Is_RTE (D_Type, RO_CA_Time) then
10498          D_Disc := Make_Integer_Literal (Loc, 1);
10499          D_Conv := Make_Function_Call (Loc,
10500            New_Reference_To (RTE (RO_CA_To_Duration), Loc),
10501            New_List (New_Copy (Expression (D_Stat))));
10502
10503       else pragma Assert (Is_RTE (D_Type, RO_RT_Time));
10504          D_Disc := Make_Integer_Literal (Loc, 2);
10505          D_Conv := Make_Function_Call (Loc,
10506            New_Reference_To (RTE (RO_RT_To_Duration), Loc),
10507            New_List (New_Copy (Expression (D_Stat))));
10508       end if;
10509
10510       D := Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
10511
10512       --  Generate:
10513       --    D : Duration;
10514
10515       Append_To (Decls,
10516         Make_Object_Declaration (Loc,
10517           Defining_Identifier =>
10518             D,
10519           Object_Definition =>
10520             New_Reference_To (Standard_Duration, Loc)));
10521
10522       M := Make_Defining_Identifier (Loc, New_Internal_Name ('M'));
10523
10524       --  Generate:
10525       --    M : Integer := (0 | 1 | 2);
10526
10527       Append_To (Decls,
10528         Make_Object_Declaration (Loc,
10529           Defining_Identifier =>
10530             M,
10531           Object_Definition =>
10532             New_Reference_To (Standard_Integer, Loc),
10533           Expression =>
10534             D_Disc));
10535
10536       --  Do the assignment at this stage only because the evaluation of the
10537       --  expression must not occur before (see ACVC C97302A).
10538
10539       Append_To (Stmts,
10540         Make_Assignment_Statement (Loc,
10541           Name =>
10542             New_Reference_To (D, Loc),
10543           Expression =>
10544             D_Conv));
10545
10546       --  Parameter block processing
10547
10548       --  Manually create the parameter block for dispatching calls. In the
10549       --  case of entries, the block has already been created during the call
10550       --  to Build_Simple_Entry_Call.
10551
10552       if Is_Disp_Select then
10553
10554          --  Tagged kind processing, generate:
10555          --    K : Ada.Tags.Tagged_Kind :=
10556          --          Ada.Tags.Get_Tagged_Kind (Ada.Tags.Tag <object>));
10557
10558          K := Build_K (Loc, Decls, Obj);
10559
10560          Blk_Typ := Build_Parameter_Block (Loc, Actuals, Formals, Decls);
10561          P := Parameter_Block_Pack
10562                 (Loc, Blk_Typ, Actuals, Formals, Decls, Stmts);
10563
10564          --  Dispatch table slot processing, generate:
10565          --    S : Integer;
10566
10567          S := Build_S (Loc, Decls);
10568
10569          --  Generate:
10570          --    S := Ada.Tags.Get_Offset_Index
10571          --           (Ada.Tags.Tag (<object>), DT_Position (Call_Ent));
10572
10573          Conc_Typ_Stmts :=
10574            New_List (Build_S_Assignment (Loc, S, Obj, Call_Ent));
10575
10576          --  Generate:
10577          --    _Disp_Timed_Select (<object>, S, P'Address, D, M, C, B);
10578
10579          --  where Obj is the controlling formal parameter, S is the dispatch
10580          --  table slot number of the dispatching operation, P is the wrapped
10581          --  parameter block, D is the duration, M is the duration mode, C is
10582          --  the call kind and B is the call status.
10583
10584          Params := New_List;
10585
10586          Append_To (Params, New_Copy_Tree (Obj));
10587          Append_To (Params, New_Reference_To (S, Loc));
10588          Append_To (Params, Make_Attribute_Reference (Loc,
10589                               Prefix => New_Reference_To (P, Loc),
10590                               Attribute_Name => Name_Address));
10591          Append_To (Params, New_Reference_To (D, Loc));
10592          Append_To (Params, New_Reference_To (M, Loc));
10593          Append_To (Params, New_Reference_To (C, Loc));
10594          Append_To (Params, New_Reference_To (B, Loc));
10595
10596          Append_To (Conc_Typ_Stmts,
10597            Make_Procedure_Call_Statement (Loc,
10598              Name =>
10599                New_Reference_To (
10600                  Find_Prim_Op (Etype (Etype (Obj)),
10601                    Name_uDisp_Timed_Select),
10602                  Loc),
10603              Parameter_Associations =>
10604                Params));
10605
10606          --  Generate:
10607          --    if C = POK_Protected_Entry
10608          --      or else C = POK_Task_Entry
10609          --    then
10610          --       Param1 := P.Param1;
10611          --       ...
10612          --       ParamN := P.ParamN;
10613          --    end if;
10614
10615          Unpack := Parameter_Block_Unpack (Loc, P, Actuals, Formals);
10616
10617          --  Generate the if statement only when the packed parameters need
10618          --  explicit assignments to their corresponding actuals.
10619
10620          if Present (Unpack) then
10621             Append_To (Conc_Typ_Stmts,
10622               Make_If_Statement (Loc,
10623
10624                 Condition =>
10625                   Make_Or_Else (Loc,
10626                     Left_Opnd =>
10627                       Make_Op_Eq (Loc,
10628                         Left_Opnd =>
10629                           New_Reference_To (C, Loc),
10630                         Right_Opnd =>
10631                           New_Reference_To (RTE (
10632                             RE_POK_Protected_Entry), Loc)),
10633                     Right_Opnd =>
10634                       Make_Op_Eq (Loc,
10635                         Left_Opnd =>
10636                           New_Reference_To (C, Loc),
10637                         Right_Opnd =>
10638                           New_Reference_To (RTE (RE_POK_Task_Entry), Loc))),
10639
10640                 Then_Statements =>
10641                   Unpack));
10642          end if;
10643
10644          --  Generate:
10645
10646          --    if B then
10647          --       if C = POK_Procedure
10648          --         or else C = POK_Protected_Procedure
10649          --         or else C = POK_Task_Procedure
10650          --       then
10651          --          <dispatching-call>
10652          --       end if;
10653          --       <triggering-statements>
10654          --    else
10655          --       <timed-statements>
10656          --    end if;
10657
10658          N_Stats := New_Copy_List_Tree (E_Stats);
10659
10660          Prepend_To (N_Stats,
10661            Make_If_Statement (Loc,
10662
10663              Condition =>
10664                Make_Or_Else (Loc,
10665                  Left_Opnd =>
10666                    Make_Op_Eq (Loc,
10667                      Left_Opnd =>
10668                        New_Reference_To (C, Loc),
10669                      Right_Opnd =>
10670                        New_Reference_To (RTE (RE_POK_Procedure), Loc)),
10671                  Right_Opnd =>
10672                    Make_Or_Else (Loc,
10673                      Left_Opnd =>
10674                        Make_Op_Eq (Loc,
10675                          Left_Opnd =>
10676                            New_Reference_To (C, Loc),
10677                          Right_Opnd =>
10678                            New_Reference_To (RTE (
10679                              RE_POK_Protected_Procedure), Loc)),
10680                      Right_Opnd =>
10681                        Make_Op_Eq (Loc,
10682                          Left_Opnd =>
10683                            New_Reference_To (C, Loc),
10684                          Right_Opnd =>
10685                            New_Reference_To (RTE (
10686                              RE_POK_Task_Procedure), Loc)))),
10687
10688              Then_Statements =>
10689                New_List (E_Call)));
10690
10691          Append_To (Conc_Typ_Stmts,
10692            Make_If_Statement (Loc,
10693              Condition => New_Reference_To (B, Loc),
10694              Then_Statements => N_Stats,
10695              Else_Statements => D_Stats));
10696
10697          --  Generate:
10698          --    <dispatching-call>;
10699          --    <triggering-statements>
10700
10701          Lim_Typ_Stmts := New_Copy_List_Tree (E_Stats);
10702          Prepend_To (Lim_Typ_Stmts, New_Copy_Tree (E_Call));
10703
10704          --  Generate:
10705          --    if K = Ada.Tags.TK_Limited_Tagged then
10706          --       Lim_Typ_Stmts
10707          --    else
10708          --       Conc_Typ_Stmts
10709          --    end if;
10710
10711          Append_To (Stmts,
10712            Make_If_Statement (Loc,
10713              Condition =>
10714                Make_Op_Eq (Loc,
10715                  Left_Opnd =>
10716                    New_Reference_To (K, Loc),
10717                  Right_Opnd =>
10718                    New_Reference_To (RTE (RE_TK_Limited_Tagged), Loc)),
10719
10720              Then_Statements =>
10721                Lim_Typ_Stmts,
10722
10723              Else_Statements =>
10724                Conc_Typ_Stmts));
10725
10726       else
10727          --  Skip assignments to temporaries created for in-out parameters.
10728          --  This makes unwarranted assumptions about the shape of the expanded
10729          --  tree for the call, and should be cleaned up ???
10730
10731          Stmt := First (Stmts);
10732          while Nkind (Stmt) /= N_Procedure_Call_Statement loop
10733             Next (Stmt);
10734          end loop;
10735
10736          --  Do the assignment at this stage only because the evaluation
10737          --  of the expression must not occur before (see ACVC C97302A).
10738
10739          Insert_Before (Stmt,
10740            Make_Assignment_Statement (Loc,
10741              Name => New_Reference_To (D, Loc),
10742              Expression => D_Conv));
10743
10744          Call   := Stmt;
10745          Params := Parameter_Associations (Call);
10746
10747          --  For a protected type, we build a Timed_Protected_Entry_Call
10748
10749          if Is_Protected_Type (Etype (Concval)) then
10750
10751             --  Create a new call statement
10752
10753             Param := First (Params);
10754             while Present (Param)
10755               and then not Is_RTE (Etype (Param), RE_Call_Modes)
10756             loop
10757                Next (Param);
10758             end loop;
10759
10760             Dummy := Remove_Next (Next (Param));
10761
10762             --  Remove garbage is following the Cancel_Param if present
10763
10764             Dummy := Next (Param);
10765
10766             --  Remove the mode of the Protected_Entry_Call call, then remove
10767             --  the Communication_Block of the Protected_Entry_Call call, and
10768             --  finally add Duration and a Delay_Mode parameter
10769
10770             pragma Assert (Present (Param));
10771             Rewrite (Param, New_Reference_To (D, Loc));
10772
10773             Rewrite (Dummy, New_Reference_To (M, Loc));
10774
10775             --  Add a Boolean flag for successful entry call
10776
10777             Append_To (Params, New_Reference_To (B, Loc));
10778
10779             case Corresponding_Runtime_Package (Etype (Concval)) is
10780                when System_Tasking_Protected_Objects_Entries =>
10781                   Rewrite (Call,
10782                     Make_Procedure_Call_Statement (Loc,
10783                       Name =>
10784                         New_Reference_To
10785                           (RTE (RE_Timed_Protected_Entry_Call), Loc),
10786                       Parameter_Associations => Params));
10787
10788                when System_Tasking_Protected_Objects_Single_Entry =>
10789                   Param := First (Params);
10790                   while Present (Param)
10791                     and then not
10792                       Is_RTE (Etype (Param), RE_Protected_Entry_Index)
10793                   loop
10794                      Next (Param);
10795                   end loop;
10796
10797                   Remove (Param);
10798
10799                   Rewrite (Call,
10800                     Make_Procedure_Call_Statement (Loc,
10801                       Name => New_Reference_To (
10802                         RTE (RE_Timed_Protected_Single_Entry_Call), Loc),
10803                       Parameter_Associations => Params));
10804
10805                when others =>
10806                   raise Program_Error;
10807             end case;
10808
10809          --  For the task case, build a Timed_Task_Entry_Call
10810
10811          else
10812             --  Create a new call statement
10813
10814             Append_To (Params, New_Reference_To (D, Loc));
10815             Append_To (Params, New_Reference_To (M, Loc));
10816             Append_To (Params, New_Reference_To (B, Loc));
10817
10818             Rewrite (Call,
10819               Make_Procedure_Call_Statement (Loc,
10820                 Name =>
10821                   New_Reference_To (RTE (RE_Timed_Task_Entry_Call), Loc),
10822                 Parameter_Associations => Params));
10823          end if;
10824
10825          Append_To (Stmts,
10826            Make_Implicit_If_Statement (N,
10827              Condition => New_Reference_To (B, Loc),
10828              Then_Statements => E_Stats,
10829              Else_Statements => D_Stats));
10830       end if;
10831
10832       Rewrite (N,
10833         Make_Block_Statement (Loc,
10834           Declarations => Decls,
10835           Handled_Statement_Sequence =>
10836             Make_Handled_Sequence_Of_Statements (Loc, Stmts)));
10837
10838       Analyze (N);
10839    end Expand_N_Timed_Entry_Call;
10840
10841    ----------------------------------------
10842    -- Expand_Protected_Body_Declarations --
10843    ----------------------------------------
10844
10845    procedure Expand_Protected_Body_Declarations
10846      (N       : Node_Id;
10847       Spec_Id : Entity_Id)
10848    is
10849    begin
10850       if No_Run_Time_Mode then
10851          Error_Msg_CRT ("protected body", N);
10852          return;
10853
10854       elsif Expander_Active then
10855
10856          --  Associate discriminals with the first subprogram or entry body to
10857          --  be expanded.
10858
10859          if Present (First_Protected_Operation (Declarations (N))) then
10860             Set_Discriminals (Parent (Spec_Id));
10861          end if;
10862       end if;
10863    end Expand_Protected_Body_Declarations;
10864
10865    -------------------------
10866    -- External_Subprogram --
10867    -------------------------
10868
10869    function External_Subprogram (E : Entity_Id) return Entity_Id is
10870       Subp : constant Entity_Id := Protected_Body_Subprogram (E);
10871
10872    begin
10873       --  The internal and external subprograms follow each other on the entity
10874       --  chain. Note that previously private operations had no separate
10875       --  external subprogram. We now create one in all cases, because a
10876       --  private operation may actually appear in an external call, through
10877       --  a 'Access reference used for a callback.
10878
10879       --  If the operation is a function that returns an anonymous access type,
10880       --  the corresponding itype appears before the operation, and must be
10881       --  skipped.
10882
10883       --  This mechanism is fragile, there should be a real link between the
10884       --  two versions of the operation, but there is no place to put it ???
10885
10886       if Is_Access_Type (Next_Entity (Subp)) then
10887          return Next_Entity (Next_Entity (Subp));
10888       else
10889          return Next_Entity (Subp);
10890       end if;
10891    end External_Subprogram;
10892
10893    ------------------------------
10894    -- Extract_Dispatching_Call --
10895    ------------------------------
10896
10897    procedure Extract_Dispatching_Call
10898      (N        : Node_Id;
10899       Call_Ent : out Entity_Id;
10900       Object   : out Entity_Id;
10901       Actuals  : out List_Id;
10902       Formals  : out List_Id)
10903    is
10904       Call_Nam : Node_Id;
10905
10906    begin
10907       pragma Assert (Nkind (N) = N_Procedure_Call_Statement);
10908
10909       if Present (Original_Node (N)) then
10910          Call_Nam := Name (Original_Node (N));
10911       else
10912          Call_Nam := Name (N);
10913       end if;
10914
10915       --  Retrieve the name of the dispatching procedure. It contains the
10916       --  dispatch table slot number.
10917
10918       loop
10919          case Nkind (Call_Nam) is
10920             when N_Identifier =>
10921                exit;
10922
10923             when N_Selected_Component =>
10924                Call_Nam := Selector_Name (Call_Nam);
10925
10926             when others =>
10927                raise Program_Error;
10928
10929          end case;
10930       end loop;
10931
10932       Actuals  := Parameter_Associations (N);
10933       Call_Ent := Entity (Call_Nam);
10934       Formals  := Parameter_Specifications (Parent (Call_Ent));
10935       Object   := First (Actuals);
10936
10937       if Present (Original_Node (Object)) then
10938          Object := Original_Node (Object);
10939       end if;
10940    end Extract_Dispatching_Call;
10941
10942    -------------------
10943    -- Extract_Entry --
10944    -------------------
10945
10946    procedure Extract_Entry
10947      (N       : Node_Id;
10948       Concval : out Node_Id;
10949       Ename   : out Node_Id;
10950       Index   : out Node_Id)
10951    is
10952       Nam : constant Node_Id := Name (N);
10953
10954    begin
10955       --  For a simple entry, the name is a selected component, with the
10956       --  prefix being the task value, and the selector being the entry.
10957
10958       if Nkind (Nam) = N_Selected_Component then
10959          Concval := Prefix (Nam);
10960          Ename   := Selector_Name (Nam);
10961          Index   := Empty;
10962
10963       --  For a member of an entry family, the name is an indexed component
10964       --  where the prefix is a selected component, whose prefix in turn is
10965       --  the task value, and whose selector is the entry family. The single
10966       --  expression in the expressions list of the indexed component is the
10967       --  subscript for the family.
10968
10969       else pragma Assert (Nkind (Nam) = N_Indexed_Component);
10970          Concval := Prefix (Prefix (Nam));
10971          Ename   := Selector_Name (Prefix (Nam));
10972          Index   := First (Expressions (Nam));
10973       end if;
10974    end Extract_Entry;
10975
10976    -------------------
10977    -- Family_Offset --
10978    -------------------
10979
10980    function Family_Offset
10981      (Loc  : Source_Ptr;
10982       Hi   : Node_Id;
10983       Lo   : Node_Id;
10984       Ttyp : Entity_Id;
10985       Cap  : Boolean) return Node_Id
10986    is
10987       Ityp : Entity_Id;
10988       Real_Hi : Node_Id;
10989       Real_Lo : Node_Id;
10990
10991       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id;
10992       --  If one of the bounds is a reference to a discriminant, replace with
10993       --  corresponding discriminal of type. Within the body of a task retrieve
10994       --  the renamed discriminant by simple visibility, using its generated
10995       --  name. Within a protected object, find the original discriminant and
10996       --  replace it with the discriminal of the current protected operation.
10997
10998       ------------------------------
10999       -- Convert_Discriminant_Ref --
11000       ------------------------------
11001
11002       function Convert_Discriminant_Ref (Bound : Node_Id) return Node_Id is
11003          Loc : constant Source_Ptr := Sloc (Bound);
11004          B   : Node_Id;
11005          D   : Entity_Id;
11006
11007       begin
11008          if Is_Entity_Name (Bound)
11009            and then Ekind (Entity (Bound)) = E_Discriminant
11010          then
11011             if Is_Task_Type (Ttyp)
11012               and then Has_Completion (Ttyp)
11013             then
11014                B := Make_Identifier (Loc, Chars (Entity (Bound)));
11015                Find_Direct_Name (B);
11016
11017             elsif Is_Protected_Type (Ttyp) then
11018                D := First_Discriminant (Ttyp);
11019                while Chars (D) /= Chars (Entity (Bound)) loop
11020                   Next_Discriminant (D);
11021                end loop;
11022
11023                B := New_Reference_To  (Discriminal (D), Loc);
11024
11025             else
11026                B := New_Reference_To (Discriminal (Entity (Bound)), Loc);
11027             end if;
11028
11029          elsif Nkind (Bound) = N_Attribute_Reference then
11030             return Bound;
11031
11032          else
11033             B := New_Copy_Tree (Bound);
11034          end if;
11035
11036          return
11037            Make_Attribute_Reference (Loc,
11038              Attribute_Name => Name_Pos,
11039              Prefix => New_Occurrence_Of (Etype (Bound), Loc),
11040              Expressions    => New_List (B));
11041       end Convert_Discriminant_Ref;
11042
11043    --  Start of processing for Family_Offset
11044
11045    begin
11046       Real_Hi := Convert_Discriminant_Ref (Hi);
11047       Real_Lo := Convert_Discriminant_Ref (Lo);
11048
11049       if Cap then
11050          if Is_Task_Type (Ttyp) then
11051             Ityp := RTE (RE_Task_Entry_Index);
11052          else
11053             Ityp := RTE (RE_Protected_Entry_Index);
11054          end if;
11055
11056          Real_Hi :=
11057            Make_Attribute_Reference (Loc,
11058              Prefix         => New_Reference_To (Ityp, Loc),
11059              Attribute_Name => Name_Min,
11060              Expressions    => New_List (
11061                Real_Hi,
11062                Make_Integer_Literal (Loc, Entry_Family_Bound - 1)));
11063
11064          Real_Lo :=
11065            Make_Attribute_Reference (Loc,
11066              Prefix         => New_Reference_To (Ityp, Loc),
11067              Attribute_Name => Name_Max,
11068              Expressions    => New_List (
11069                Real_Lo,
11070                Make_Integer_Literal (Loc, -Entry_Family_Bound)));
11071       end if;
11072
11073       return Make_Op_Subtract (Loc, Real_Hi, Real_Lo);
11074    end Family_Offset;
11075
11076    -----------------
11077    -- Family_Size --
11078    -----------------
11079
11080    function Family_Size
11081      (Loc  : Source_Ptr;
11082       Hi   : Node_Id;
11083       Lo   : Node_Id;
11084       Ttyp : Entity_Id;
11085       Cap  : Boolean) return Node_Id
11086    is
11087       Ityp : Entity_Id;
11088
11089    begin
11090       if Is_Task_Type (Ttyp) then
11091          Ityp := RTE (RE_Task_Entry_Index);
11092       else
11093          Ityp := RTE (RE_Protected_Entry_Index);
11094       end if;
11095
11096       return
11097         Make_Attribute_Reference (Loc,
11098           Prefix         => New_Reference_To (Ityp, Loc),
11099           Attribute_Name => Name_Max,
11100           Expressions    => New_List (
11101             Make_Op_Add (Loc,
11102               Left_Opnd  =>
11103                 Family_Offset (Loc, Hi, Lo, Ttyp, Cap),
11104               Right_Opnd =>
11105                 Make_Integer_Literal (Loc, 1)),
11106             Make_Integer_Literal (Loc, 0)));
11107    end Family_Size;
11108
11109    -----------------------------------
11110    -- Find_Task_Or_Protected_Pragma --
11111    -----------------------------------
11112
11113    function Find_Task_Or_Protected_Pragma
11114      (T : Node_Id;
11115       P : Name_Id) return Node_Id
11116    is
11117       N : Node_Id;
11118
11119    begin
11120       N := First (Visible_Declarations (T));
11121       while Present (N) loop
11122          if Nkind (N) = N_Pragma then
11123             if Pragma_Name (N) = P then
11124                return N;
11125
11126             elsif P = Name_Priority
11127               and then Pragma_Name (N) = Name_Interrupt_Priority
11128             then
11129                return N;
11130
11131             else
11132                Next (N);
11133             end if;
11134
11135          else
11136             Next (N);
11137          end if;
11138       end loop;
11139
11140       N := First (Private_Declarations (T));
11141       while Present (N) loop
11142          if Nkind (N) = N_Pragma then
11143             if Pragma_Name (N) = P then
11144                return N;
11145
11146             elsif P = Name_Priority
11147               and then Pragma_Name (N) = Name_Interrupt_Priority
11148             then
11149                return N;
11150
11151             else
11152                Next (N);
11153             end if;
11154
11155          else
11156             Next (N);
11157          end if;
11158       end loop;
11159
11160       raise Program_Error;
11161    end Find_Task_Or_Protected_Pragma;
11162
11163    -------------------------------
11164    -- First_Protected_Operation --
11165    -------------------------------
11166
11167    function First_Protected_Operation (D : List_Id) return Node_Id is
11168       First_Op : Node_Id;
11169
11170    begin
11171       First_Op := First (D);
11172       while Present (First_Op)
11173         and then not Nkind_In (First_Op, N_Subprogram_Body, N_Entry_Body)
11174       loop
11175          Next (First_Op);
11176       end loop;
11177
11178       return First_Op;
11179    end First_Protected_Operation;
11180
11181    ---------------------------------------
11182    -- Install_Private_Data_Declarations --
11183    ---------------------------------------
11184
11185    procedure Install_Private_Data_Declarations
11186      (Loc      : Source_Ptr;
11187       Spec_Id  : Entity_Id;
11188       Conc_Typ : Entity_Id;
11189       Body_Nod : Node_Id;
11190       Decls    : List_Id;
11191       Barrier  : Boolean := False;
11192       Family   : Boolean := False)
11193    is
11194       Is_Protected : constant Boolean := Is_Protected_Type (Conc_Typ);
11195       Decl         : Node_Id;
11196       Def          : Node_Id;
11197       Insert_Node  : Node_Id := Empty;
11198       Obj_Ent      : Entity_Id;
11199
11200       procedure Add (Decl : Node_Id);
11201       --  Add a single declaration after Insert_Node. If this is the first
11202       --  addition, Decl is added to the front of Decls and it becomes the
11203       --  insertion node.
11204
11205       function Replace_Bound (Bound : Node_Id) return Node_Id;
11206       --  The bounds of an entry index may depend on discriminants, create a
11207       --  reference to the corresponding prival. Otherwise return a duplicate
11208       --  of the original bound.
11209
11210       ---------
11211       -- Add --
11212       ---------
11213
11214       procedure Add (Decl : Node_Id) is
11215       begin
11216          if No (Insert_Node) then
11217             Prepend_To (Decls, Decl);
11218          else
11219             Insert_After (Insert_Node, Decl);
11220          end if;
11221
11222          Insert_Node := Decl;
11223       end Add;
11224
11225       --------------------------
11226       -- Replace_Discriminant --
11227       --------------------------
11228
11229       function Replace_Bound (Bound : Node_Id) return Node_Id is
11230       begin
11231          if Nkind (Bound) = N_Identifier
11232            and then Is_Discriminal (Entity (Bound))
11233          then
11234             return Make_Identifier (Loc, Chars (Entity (Bound)));
11235          else
11236             return Duplicate_Subexpr (Bound);
11237          end if;
11238       end Replace_Bound;
11239
11240    --  Start of processing for Install_Private_Data_Declarations
11241
11242    begin
11243       --  Step 1: Retrieve the concurrent object entity. Obj_Ent can denote
11244       --  formal parameter _O, _object or _task depending on the context.
11245
11246       Obj_Ent := Concurrent_Object (Spec_Id, Conc_Typ);
11247
11248       --  Special processing of _O for barrier functions, protected entries
11249       --  and families.
11250
11251       if Barrier
11252         or else
11253           (Is_Protected
11254              and then
11255                (Ekind (Spec_Id) = E_Entry
11256                   or else Ekind (Spec_Id) = E_Entry_Family))
11257       then
11258          declare
11259             Conc_Rec : constant Entity_Id :=
11260                          Corresponding_Record_Type (Conc_Typ);
11261             Typ_Id   : constant Entity_Id :=
11262                          Make_Defining_Identifier (Loc,
11263                            New_External_Name (Chars (Conc_Rec), 'P'));
11264          begin
11265             --  Generate:
11266             --    type prot_typVP is access prot_typV;
11267
11268             Decl :=
11269               Make_Full_Type_Declaration (Loc,
11270                 Defining_Identifier => Typ_Id,
11271                 Type_Definition     =>
11272                   Make_Access_To_Object_Definition (Loc,
11273                     Subtype_Indication =>
11274                       New_Reference_To (Conc_Rec, Loc)));
11275             Add (Decl);
11276
11277             --  Generate:
11278             --    _object : prot_typVP := prot_typV (_O);
11279
11280             Decl :=
11281               Make_Object_Declaration (Loc,
11282                 Defining_Identifier =>
11283                   Make_Defining_Identifier (Loc, Name_uObject),
11284                 Object_Definition   => New_Reference_To (Typ_Id, Loc),
11285                 Expression          =>
11286                   Unchecked_Convert_To (Typ_Id,
11287                     New_Reference_To (Obj_Ent, Loc)));
11288             Add (Decl);
11289
11290             --  Set the reference to the concurrent object
11291
11292             Obj_Ent := Defining_Identifier (Decl);
11293          end;
11294       end if;
11295
11296       --  Step 2: Create the Protection object and build its declaration for
11297       --  any protected entry (family) of subprogram.
11298
11299       if Is_Protected then
11300          declare
11301             Prot_Ent : constant Entity_Id :=
11302                          Make_Defining_Identifier (Loc,
11303                            New_Internal_Name ('R'));
11304             Prot_Typ : RE_Id;
11305
11306          begin
11307             Set_Protection_Object (Spec_Id, Prot_Ent);
11308
11309             --  Determine the proper protection type
11310
11311             if Has_Attach_Handler (Conc_Typ)
11312               and then not Restricted_Profile
11313             then
11314                Prot_Typ := RE_Static_Interrupt_Protection;
11315
11316             elsif Has_Interrupt_Handler (Conc_Typ) then
11317                Prot_Typ := RE_Dynamic_Interrupt_Protection;
11318
11319             --  The type has explicit entries or generated primitive entry
11320             --  wrappers.
11321
11322             elsif Has_Entries (Conc_Typ)
11323               or else
11324                 (Ada_Version >= Ada_05
11325                    and then Present (Interface_List (Parent (Conc_Typ))))
11326             then
11327                case Corresponding_Runtime_Package (Conc_Typ) is
11328                   when System_Tasking_Protected_Objects_Entries =>
11329                      Prot_Typ := RE_Protection_Entries;
11330
11331                   when System_Tasking_Protected_Objects_Single_Entry =>
11332                      Prot_Typ := RE_Protection_Entry;
11333
11334                   when others =>
11335                      raise Program_Error;
11336                end case;
11337
11338             else
11339                Prot_Typ := RE_Protection;
11340             end if;
11341
11342             --  Generate:
11343             --    conc_typR : protection_typ renames _object._object;
11344
11345             Decl :=
11346               Make_Object_Renaming_Declaration (Loc,
11347                 Defining_Identifier => Prot_Ent,
11348                 Subtype_Mark =>
11349                   New_Reference_To (RTE (Prot_Typ), Loc),
11350                 Name =>
11351                   Make_Selected_Component (Loc,
11352                     Prefix =>
11353                       New_Reference_To (Obj_Ent, Loc),
11354                     Selector_Name =>
11355                       Make_Identifier (Loc, Name_uObject)));
11356             Add (Decl);
11357          end;
11358       end if;
11359
11360       --  Step 3: Add discriminant renamings (if any)
11361
11362       if Has_Discriminants (Conc_Typ) then
11363          declare
11364             D : Entity_Id;
11365
11366          begin
11367             D := First_Discriminant (Conc_Typ);
11368             while Present (D) loop
11369
11370                --  Adjust the source location
11371
11372                Set_Sloc (Discriminal (D), Loc);
11373
11374                --  Generate:
11375                --    discr_name : discr_typ renames _object.discr_name;
11376                --      or
11377                --    discr_name : discr_typ renames _task.discr_name;
11378
11379                Decl :=
11380                  Make_Object_Renaming_Declaration (Loc,
11381                    Defining_Identifier => Discriminal (D),
11382                    Subtype_Mark        => New_Reference_To (Etype (D), Loc),
11383                    Name                =>
11384                      Make_Selected_Component (Loc,
11385                        Prefix        => New_Reference_To (Obj_Ent, Loc),
11386                        Selector_Name => Make_Identifier (Loc, Chars (D))));
11387                Add (Decl);
11388
11389                Next_Discriminant (D);
11390             end loop;
11391          end;
11392       end if;
11393
11394       --  Step 4: Add private component renamings (if any)
11395
11396       if Is_Protected then
11397          Def := Protected_Definition (Parent (Conc_Typ));
11398
11399          if Present (Private_Declarations (Def)) then
11400             declare
11401                Comp    : Node_Id;
11402                Comp_Id : Entity_Id;
11403                Decl_Id : Entity_Id;
11404
11405             begin
11406                Comp := First (Private_Declarations (Def));
11407                while Present (Comp) loop
11408                   if Nkind (Comp) = N_Component_Declaration then
11409                      Comp_Id := Defining_Identifier (Comp);
11410                      Decl_Id :=
11411                        Make_Defining_Identifier (Loc, Chars (Comp_Id));
11412
11413                      --  Minimal decoration
11414
11415                      if Ekind (Spec_Id) = E_Function then
11416                         Set_Ekind (Decl_Id, E_Constant);
11417                      else
11418                         Set_Ekind (Decl_Id, E_Variable);
11419                      end if;
11420
11421                      Set_Prival      (Comp_Id, Decl_Id);
11422                      Set_Prival_Link (Decl_Id, Comp_Id);
11423                      Set_Is_Aliased  (Decl_Id, Is_Aliased (Comp_Id));
11424
11425                      --  Generate:
11426                      --    comp_name : comp_typ renames _object.comp_name;
11427
11428                      Decl :=
11429                        Make_Object_Renaming_Declaration (Loc,
11430                          Defining_Identifier => Decl_Id,
11431                          Subtype_Mark =>
11432                            New_Reference_To (Etype (Comp_Id), Loc),
11433                          Name =>
11434                            Make_Selected_Component (Loc,
11435                              Prefix =>
11436                                New_Reference_To (Obj_Ent, Loc),
11437                              Selector_Name =>
11438                                Make_Identifier (Loc, Chars (Comp_Id))));
11439                      Add (Decl);
11440                   end if;
11441
11442                   Next (Comp);
11443                end loop;
11444             end;
11445          end if;
11446       end if;
11447
11448       --  Step 5: Add the declaration of the entry index and the associated
11449       --  type for barrier functions and entry families.
11450
11451       if (Barrier and then Family)
11452         or else Ekind (Spec_Id) = E_Entry_Family
11453       then
11454          declare
11455             E         : constant Entity_Id := Index_Object (Spec_Id);
11456             Index     : constant Entity_Id :=
11457                           Defining_Identifier (
11458                             Entry_Index_Specification (
11459                               Entry_Body_Formal_Part (Body_Nod)));
11460             Index_Con : constant Entity_Id :=
11461                           Make_Defining_Identifier (Loc, Chars (Index));
11462             High      : Node_Id;
11463             Index_Typ : Entity_Id;
11464             Low       : Node_Id;
11465
11466          begin
11467             --  Minimal decoration
11468
11469             Set_Ekind                (Index_Con, E_Constant);
11470             Set_Entry_Index_Constant (Index, Index_Con);
11471             Set_Discriminal_Link     (Index_Con, Index);
11472
11473             --  Retrieve the bounds of the entry family
11474
11475             High := Type_High_Bound (Etype (Index));
11476             Low  := Type_Low_Bound  (Etype (Index));
11477
11478             --  In the simple case the entry family is given by a subtype
11479             --  mark and the index constant has the same type.
11480
11481             if Is_Entity_Name (Original_Node (
11482                  Discrete_Subtype_Definition (Parent (Index))))
11483             then
11484                Index_Typ := Etype (Index);
11485
11486             --  Otherwise a new subtype declaration is required
11487
11488             else
11489                High := Replace_Bound (High);
11490                Low  := Replace_Bound (Low);
11491
11492                Index_Typ :=
11493                  Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
11494
11495                --  Generate:
11496                --    subtype Jnn is <Etype of Index> range Low .. High;
11497
11498                Decl :=
11499                  Make_Subtype_Declaration (Loc,
11500                    Defining_Identifier => Index_Typ,
11501                    Subtype_Indication =>
11502                      Make_Subtype_Indication (Loc,
11503                        Subtype_Mark =>
11504                          New_Reference_To (Base_Type (Etype (Index)), Loc),
11505                        Constraint =>
11506                          Make_Range_Constraint (Loc,
11507                            Range_Expression =>
11508                              Make_Range (Loc, Low, High))));
11509                Add (Decl);
11510             end if;
11511
11512             Set_Etype (Index_Con, Index_Typ);
11513
11514             --  Create the object which designates the index:
11515             --    J : constant Jnn :=
11516             --          Jnn'Val (_E - <index expr> + Jnn'Pos (Jnn'First));
11517             --
11518             --  where Jnn is the subtype created above or the original type of
11519             --  the index, _E is a formal of the protected body subprogram and
11520             --  <index expr> is the index of the first family member.
11521
11522             Decl :=
11523               Make_Object_Declaration (Loc,
11524                 Defining_Identifier => Index_Con,
11525                 Constant_Present => True,
11526                 Object_Definition =>
11527                   New_Reference_To (Index_Typ, Loc),
11528
11529                 Expression =>
11530                   Make_Attribute_Reference (Loc,
11531                     Prefix =>
11532                       New_Reference_To (Index_Typ, Loc),
11533                     Attribute_Name => Name_Val,
11534
11535                     Expressions => New_List (
11536
11537                       Make_Op_Add (Loc,
11538                         Left_Opnd =>
11539                           Make_Op_Subtract (Loc,
11540                             Left_Opnd =>
11541                               New_Reference_To (E, Loc),
11542                             Right_Opnd =>
11543                               Entry_Index_Expression (Loc,
11544                                 Defining_Identifier (Body_Nod),
11545                                 Empty, Conc_Typ)),
11546
11547                         Right_Opnd =>
11548                           Make_Attribute_Reference (Loc,
11549                             Prefix =>
11550                               New_Reference_To (Index_Typ, Loc),
11551                             Attribute_Name => Name_Pos,
11552                             Expressions => New_List (
11553                               Make_Attribute_Reference (Loc,
11554                                 Prefix =>
11555                                   New_Reference_To (Index_Typ, Loc),
11556                                 Attribute_Name => Name_First)))))));
11557             Add (Decl);
11558          end;
11559       end if;
11560    end Install_Private_Data_Declarations;
11561
11562    ---------------------------------
11563    -- Is_Potentially_Large_Family --
11564    ---------------------------------
11565
11566    function Is_Potentially_Large_Family
11567      (Base_Index : Entity_Id;
11568       Conctyp    : Entity_Id;
11569       Lo         : Node_Id;
11570       Hi         : Node_Id) return Boolean
11571    is
11572    begin
11573       return Scope (Base_Index) = Standard_Standard
11574         and then Base_Index = Base_Type (Standard_Integer)
11575         and then Has_Discriminants (Conctyp)
11576         and then Present
11577           (Discriminant_Default_Value (First_Discriminant (Conctyp)))
11578         and then
11579           (Denotes_Discriminant (Lo, True)
11580             or else Denotes_Discriminant (Hi, True));
11581    end Is_Potentially_Large_Family;
11582
11583    -------------------------------------
11584    -- Is_Private_Primitive_Subprogram --
11585    -------------------------------------
11586
11587    function Is_Private_Primitive_Subprogram (Id : Entity_Id) return Boolean is
11588    begin
11589       return
11590         (Ekind (Id) = E_Function or else Ekind (Id) = E_Procedure)
11591           and then Is_Private_Primitive (Id);
11592    end Is_Private_Primitive_Subprogram;
11593
11594    ------------------
11595    -- Index_Object --
11596    ------------------
11597
11598    function Index_Object (Spec_Id : Entity_Id) return Entity_Id is
11599       Bod_Subp : constant Entity_Id := Protected_Body_Subprogram (Spec_Id);
11600       Formal   : Entity_Id;
11601
11602    begin
11603       Formal := First_Formal (Bod_Subp);
11604       while Present (Formal) loop
11605
11606          --  Look for formal parameter _E
11607
11608          if Chars (Formal) = Name_uE then
11609             return Formal;
11610          end if;
11611
11612          Next_Formal (Formal);
11613       end loop;
11614
11615       --  A protected body subprogram should always have the parameter in
11616       --  question.
11617
11618       raise Program_Error;
11619    end Index_Object;
11620
11621    --------------------------------
11622    -- Make_Initialize_Protection --
11623    --------------------------------
11624
11625    function Make_Initialize_Protection
11626      (Protect_Rec : Entity_Id) return List_Id
11627    is
11628       Loc         : constant Source_Ptr := Sloc (Protect_Rec);
11629       P_Arr       : Entity_Id;
11630       Pdef        : Node_Id;
11631       Pdec        : Node_Id;
11632       Ptyp        : constant Node_Id :=
11633                       Corresponding_Concurrent_Type (Protect_Rec);
11634       Args        : List_Id;
11635       L           : constant List_Id := New_List;
11636       Has_Entry   : constant Boolean := Has_Entries (Ptyp);
11637       Restricted  : constant Boolean := Restricted_Profile;
11638
11639    begin
11640       --  We may need two calls to properly initialize the object, one to
11641       --  Initialize_Protection, and possibly one to Install_Handlers if we
11642       --  have a pragma Attach_Handler.
11643
11644       --  Get protected declaration. In the case of a task type declaration,
11645       --  this is simply the parent of the protected type entity. In the single
11646       --  protected object declaration, this parent will be the implicit type,
11647       --  and we can find the corresponding single protected object declaration
11648       --  by searching forward in the declaration list in the tree.
11649
11650       --  Is the test for N_Single_Protected_Declaration needed here??? Nodes
11651       --  of this type should have been removed during semantic analysis.
11652
11653       Pdec := Parent (Ptyp);
11654       while not Nkind_In (Pdec, N_Protected_Type_Declaration,
11655                                 N_Single_Protected_Declaration)
11656       loop
11657          Next (Pdec);
11658       end loop;
11659
11660       --  Now we can find the object definition from this declaration
11661
11662       Pdef := Protected_Definition (Pdec);
11663
11664       --  Build the parameter list for the call. Note that _Init is the name
11665       --  of the formal for the object to be initialized, which is the task
11666       --  value record itself.
11667
11668       Args := New_List;
11669
11670       --  Object parameter. This is a pointer to the object of type
11671       --  Protection used by the GNARL to control the protected object.
11672
11673       Append_To (Args,
11674         Make_Attribute_Reference (Loc,
11675           Prefix =>
11676             Make_Selected_Component (Loc,
11677               Prefix => Make_Identifier (Loc, Name_uInit),
11678               Selector_Name => Make_Identifier (Loc, Name_uObject)),
11679           Attribute_Name => Name_Unchecked_Access));
11680
11681       --  Priority parameter. Set to Unspecified_Priority unless there is a
11682       --  priority pragma, in which case we take the value from the pragma,
11683       --  or there is an interrupt pragma and no priority pragma, and we
11684       --  set the ceiling to Interrupt_Priority'Last, an implementation-
11685       --  defined value, see D.3(10).
11686
11687       if Present (Pdef)
11688         and then Has_Priority_Pragma (Pdef)
11689       then
11690          declare
11691             Prio : constant Node_Id :=
11692                      Expression
11693                        (First
11694                           (Pragma_Argument_Associations
11695                              (Find_Task_Or_Protected_Pragma
11696                                 (Pdef, Name_Priority))));
11697             Temp : Entity_Id;
11698
11699          begin
11700             --  If priority is a static expression, then we can duplicate it
11701             --  with no problem and simply append it to the argument list.
11702
11703             if Is_Static_Expression (Prio) then
11704                Append_To (Args,
11705                           Duplicate_Subexpr_No_Checks (Prio));
11706
11707             --  Otherwise, the priority may be a per-object expression, if it
11708             --  depends on a discriminant of the type. In this case, create
11709             --  local variable to capture the expression. Note that it is
11710             --  really necessary to create this variable explicitly. It might
11711             --  be thought that removing side effects would the appropriate
11712             --  approach, but that could generate declarations improperly
11713             --  placed in the enclosing scope.
11714
11715             --  Note: Use System.Any_Priority as the expected type for the
11716             --  non-static priority expression, in case the expression has not
11717             --  been analyzed yet (as occurs for example with pragma
11718             --  Interrupt_Priority).
11719
11720             else
11721                Temp :=
11722                  Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
11723
11724                Append_To (L,
11725                   Make_Object_Declaration (Loc,
11726                      Defining_Identifier => Temp,
11727                      Object_Definition   =>
11728                        New_Occurrence_Of (RTE (RE_Any_Priority), Loc),
11729                      Expression          => Relocate_Node (Prio)));
11730
11731                   Append_To (Args, New_Occurrence_Of (Temp, Loc));
11732             end if;
11733          end;
11734
11735       --  When no priority is specified but an xx_Handler pragma is, we default
11736       --  to System.Interrupts.Default_Interrupt_Priority, see D.3(10).
11737
11738       elsif Has_Interrupt_Handler (Ptyp)
11739         or else Has_Attach_Handler (Ptyp)
11740       then
11741          Append_To (Args,
11742            New_Reference_To (RTE (RE_Default_Interrupt_Priority), Loc));
11743
11744       --  Normal case, no priority or xx_Handler specified, default priority
11745
11746       else
11747          Append_To (Args,
11748            New_Reference_To (RTE (RE_Unspecified_Priority), Loc));
11749       end if;
11750
11751       --  Test for Compiler_Info parameter. This parameter allows entry body
11752       --  procedures and barrier functions to be called from the runtime. It
11753       --  is a pointer to the record generated by the compiler to represent
11754       --  the protected object.
11755
11756       if Has_Entry
11757         or else Has_Interrupt_Handler (Ptyp)
11758         or else Has_Attach_Handler (Ptyp)
11759         or else Has_Interfaces (Protect_Rec)
11760       then
11761          declare
11762             Pkg_Id      : constant RTU_Id  :=
11763                             Corresponding_Runtime_Package (Ptyp);
11764             Called_Subp : RE_Id;
11765
11766          begin
11767             case Pkg_Id is
11768                when System_Tasking_Protected_Objects_Entries =>
11769                   Called_Subp := RE_Initialize_Protection_Entries;
11770
11771                when System_Tasking_Protected_Objects =>
11772                   Called_Subp := RE_Initialize_Protection;
11773
11774                when System_Tasking_Protected_Objects_Single_Entry =>
11775                   Called_Subp := RE_Initialize_Protection_Entry;
11776
11777                when others =>
11778                   raise Program_Error;
11779             end case;
11780
11781             if Has_Entry or else not Restricted then
11782                Append_To (Args,
11783                  Make_Attribute_Reference (Loc,
11784                    Prefix => Make_Identifier (Loc, Name_uInit),
11785                    Attribute_Name => Name_Address));
11786             end if;
11787
11788             --  Entry_Bodies parameter. This is a pointer to an array of
11789             --  pointers to the entry body procedures and barrier functions of
11790             --  the object. If the protected type has no entries this object
11791             --  will not exist, in this case, pass a null.
11792
11793             if Has_Entry then
11794                P_Arr := Entry_Bodies_Array (Ptyp);
11795
11796                Append_To (Args,
11797                  Make_Attribute_Reference (Loc,
11798                    Prefix => New_Reference_To (P_Arr, Loc),
11799                    Attribute_Name => Name_Unrestricted_Access));
11800
11801                if Pkg_Id = System_Tasking_Protected_Objects_Entries then
11802
11803                   --  Find index mapping function (clumsy but ok for now)
11804
11805                   while Ekind (P_Arr) /= E_Function loop
11806                      Next_Entity (P_Arr);
11807                   end loop;
11808
11809                   Append_To (Args,
11810                     Make_Attribute_Reference (Loc,
11811                       Prefix =>
11812                         New_Reference_To (P_Arr, Loc),
11813                       Attribute_Name => Name_Unrestricted_Access));
11814
11815                   --  Build_Entry_Names generation flag. When set to true, the
11816                   --  runtime will allocate an array to hold the string names
11817                   --  of protected entries.
11818
11819                   if not Restricted_Profile then
11820                      if Entry_Names_OK then
11821                         Append_To (Args,
11822                           New_Reference_To (Standard_True, Loc));
11823                      else
11824                         Append_To (Args,
11825                           New_Reference_To (Standard_False, Loc));
11826                      end if;
11827                   end if;
11828                end if;
11829
11830             elsif Pkg_Id = System_Tasking_Protected_Objects_Single_Entry then
11831                Append_To (Args, Make_Null (Loc));
11832
11833             elsif Pkg_Id = System_Tasking_Protected_Objects_Entries then
11834                Append_To (Args, Make_Null (Loc));
11835                Append_To (Args, Make_Null (Loc));
11836                Append_To (Args, New_Reference_To (Standard_False, Loc));
11837             end if;
11838
11839             Append_To (L,
11840               Make_Procedure_Call_Statement (Loc,
11841                 Name => New_Reference_To (RTE (Called_Subp), Loc),
11842                 Parameter_Associations => Args));
11843          end;
11844       else
11845          Append_To (L,
11846            Make_Procedure_Call_Statement (Loc,
11847              Name => New_Reference_To (RTE (RE_Initialize_Protection), Loc),
11848              Parameter_Associations => Args));
11849       end if;
11850
11851       if Has_Attach_Handler (Ptyp) then
11852
11853          --  We have a list of N Attach_Handler (ProcI, ExprI), and we have to
11854          --  make the following call:
11855
11856          --  Install_Handlers (_object,
11857          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
11858
11859          --  or, in the case of Ravenscar:
11860
11861          --  Install_Restricted_Handlers
11862          --    ((Expr1, Proc1'access), ...., (ExprN, ProcN'access));
11863
11864          declare
11865             Args  : constant List_Id := New_List;
11866             Table : constant List_Id := New_List;
11867             Ritem : Node_Id          := First_Rep_Item (Ptyp);
11868
11869          begin
11870             --  Build the Attach_Handler table argument
11871
11872             while Present (Ritem) loop
11873                if Nkind (Ritem) = N_Pragma
11874                  and then Pragma_Name (Ritem) = Name_Attach_Handler
11875                then
11876                   declare
11877                      Handler : constant Node_Id :=
11878                                  First (Pragma_Argument_Associations (Ritem));
11879
11880                      Interrupt : constant Node_Id := Next (Handler);
11881                      Expr      : constant Node_Id := Expression (Interrupt);
11882
11883                   begin
11884                      Append_To (Table,
11885                        Make_Aggregate (Loc, Expressions => New_List (
11886                          Unchecked_Convert_To
11887                           (RTE (RE_System_Interrupt_Id), Expr),
11888                          Make_Attribute_Reference (Loc,
11889                            Prefix => Make_Selected_Component (Loc,
11890                               Make_Identifier (Loc, Name_uInit),
11891                               Duplicate_Subexpr_No_Checks
11892                                 (Expression (Handler))),
11893                            Attribute_Name => Name_Access))));
11894                   end;
11895                end if;
11896
11897                Next_Rep_Item (Ritem);
11898             end loop;
11899
11900             --  Append the table argument we just built
11901
11902             Append_To (Args, Make_Aggregate (Loc, Table));
11903
11904             --  Append the Install_Handlers (or Install_Restricted_Handlers)
11905             --  call to the statements.
11906
11907             if Restricted then
11908                --  Call a simplified version of Install_Handlers to be used
11909                --  when the Ravenscar restrictions are in effect
11910                --  (Install_Restricted_Handlers).
11911
11912                Append_To (L,
11913                  Make_Procedure_Call_Statement (Loc,
11914                    Name =>
11915                      New_Reference_To
11916                         (RTE (RE_Install_Restricted_Handlers), Loc),
11917                    Parameter_Associations => Args));
11918
11919             else
11920                --  First, prepends the _object argument
11921
11922                Prepend_To (Args,
11923                  Make_Attribute_Reference (Loc,
11924                    Prefix =>
11925                      Make_Selected_Component (Loc,
11926                        Prefix => Make_Identifier (Loc, Name_uInit),
11927                        Selector_Name => Make_Identifier (Loc, Name_uObject)),
11928                    Attribute_Name => Name_Unchecked_Access));
11929
11930                --  Then, insert call to Install_Handlers
11931
11932                Append_To (L,
11933                  Make_Procedure_Call_Statement (Loc,
11934                    Name => New_Reference_To (RTE (RE_Install_Handlers), Loc),
11935                    Parameter_Associations => Args));
11936             end if;
11937          end;
11938       end if;
11939
11940       return L;
11941    end Make_Initialize_Protection;
11942
11943    ---------------------------
11944    -- Make_Task_Create_Call --
11945    ---------------------------
11946
11947    function Make_Task_Create_Call (Task_Rec : Entity_Id) return Node_Id is
11948       Loc    : constant Source_Ptr := Sloc (Task_Rec);
11949       Args   : List_Id;
11950       Ecount : Node_Id;
11951       Name   : Node_Id;
11952       Tdec   : Node_Id;
11953       Tdef   : Node_Id;
11954       Tnam   : Name_Id;
11955       Ttyp   : Node_Id;
11956
11957    begin
11958       Ttyp := Corresponding_Concurrent_Type (Task_Rec);
11959       Tnam := Chars (Ttyp);
11960
11961       --  Get task declaration. In the case of a task type declaration, this is
11962       --  simply the parent of the task type entity. In the single task
11963       --  declaration, this parent will be the implicit type, and we can find
11964       --  the corresponding single task declaration by searching forward in the
11965       --  declaration list in the tree.
11966
11967       --  Is the test for N_Single_Task_Declaration needed here??? Nodes of
11968       --  this type should have been removed during semantic analysis.
11969
11970       Tdec := Parent (Ttyp);
11971       while not Nkind_In (Tdec, N_Task_Type_Declaration,
11972                                 N_Single_Task_Declaration)
11973       loop
11974          Next (Tdec);
11975       end loop;
11976
11977       --  Now we can find the task definition from this declaration
11978
11979       Tdef := Task_Definition (Tdec);
11980
11981       --  Build the parameter list for the call. Note that _Init is the name
11982       --  of the formal for the object to be initialized, which is the task
11983       --  value record itself.
11984
11985       Args := New_List;
11986
11987       --  Priority parameter. Set to Unspecified_Priority unless there is a
11988       --  priority pragma, in which case we take the value from the pragma.
11989
11990       if Present (Tdef) and then Has_Priority_Pragma (Tdef) then
11991          Append_To (Args,
11992            Make_Selected_Component (Loc,
11993              Prefix => Make_Identifier (Loc, Name_uInit),
11994              Selector_Name => Make_Identifier (Loc, Name_uPriority)));
11995       else
11996          Append_To (Args,
11997            New_Reference_To (RTE (RE_Unspecified_Priority), Loc));
11998       end if;
11999
12000       --  Optional Stack parameter
12001
12002       if Restricted_Profile then
12003
12004          --  If the stack has been preallocated by the expander then
12005          --  pass its address. Otherwise, pass a null address.
12006
12007          if Preallocated_Stacks_On_Target then
12008             Append_To (Args,
12009               Make_Attribute_Reference (Loc,
12010                 Prefix         => Make_Selected_Component (Loc,
12011                   Prefix        => Make_Identifier (Loc, Name_uInit),
12012                   Selector_Name =>
12013                     Make_Identifier (Loc, Name_uStack)),
12014                 Attribute_Name => Name_Address));
12015
12016          else
12017             Append_To (Args,
12018               New_Reference_To (RTE (RE_Null_Address), Loc));
12019          end if;
12020       end if;
12021
12022       --  Size parameter. If no Storage_Size pragma is present, then
12023       --  the size is taken from the taskZ variable for the type, which
12024       --  is either Unspecified_Size, or has been reset by the use of
12025       --  a Storage_Size attribute definition clause. If a pragma is
12026       --  present, then the size is taken from the _Size field of the
12027       --  task value record, which was set from the pragma value.
12028
12029       if Present (Tdef)
12030         and then Has_Storage_Size_Pragma (Tdef)
12031       then
12032          Append_To (Args,
12033            Make_Selected_Component (Loc,
12034              Prefix => Make_Identifier (Loc, Name_uInit),
12035              Selector_Name => Make_Identifier (Loc, Name_uSize)));
12036
12037       else
12038          Append_To (Args,
12039            New_Reference_To (Storage_Size_Variable (Ttyp), Loc));
12040       end if;
12041
12042       --  Task_Info parameter. Set to Unspecified_Task_Info unless there is a
12043       --  Task_Info pragma, in which case we take the value from the pragma.
12044
12045       if Present (Tdef)
12046         and then Has_Task_Info_Pragma (Tdef)
12047       then
12048          Append_To (Args,
12049            Make_Selected_Component (Loc,
12050              Prefix => Make_Identifier (Loc, Name_uInit),
12051              Selector_Name => Make_Identifier (Loc, Name_uTask_Info)));
12052
12053       else
12054          Append_To (Args,
12055            New_Reference_To (RTE (RE_Unspecified_Task_Info), Loc));
12056       end if;
12057
12058       if not Restricted_Profile then
12059
12060          --  Deadline parameter. If no Relative_Deadline pragma is present,
12061          --  then the deadline is Time_Span_Zero. If a pragma is present, then
12062          --  the deadline is taken from the _Relative_Deadline field of the
12063          --  task value record, which was set from the pragma value. Note that
12064          --  this parameter must not be generated for the restricted profiles
12065          --  since Ravenscar does not allow deadlines.
12066
12067          --  Case where pragma Relative_Deadline applies: use given value
12068
12069          if Present (Tdef) and then Has_Relative_Deadline_Pragma (Tdef) then
12070             Append_To (Args,
12071               Make_Selected_Component (Loc,
12072                 Prefix => Make_Identifier (Loc, Name_uInit),
12073                 Selector_Name =>
12074                   Make_Identifier (Loc, Name_uRelative_Deadline)));
12075
12076          --  No pragma Relative_Deadline apply to the task
12077
12078          else
12079             Append_To (Args,
12080               New_Reference_To (RTE (RE_Time_Span_Zero), Loc));
12081          end if;
12082
12083          --  Number of entries. This is an expression of the form:
12084
12085          --    n + _Init.a'Length + _Init.a'B'Length + ...
12086
12087          --  where a,b... are the entry family names for the task definition
12088
12089          Ecount :=
12090            Build_Entry_Count_Expression
12091              (Ttyp,
12092               Component_Items
12093                 (Component_List
12094                    (Type_Definition
12095                       (Parent (Corresponding_Record_Type (Ttyp))))),
12096               Loc);
12097          Append_To (Args, Ecount);
12098
12099          --  Master parameter. This is a reference to the _Master parameter of
12100          --  the initialization procedure, except in the case of the pragma
12101          --  Restrictions (No_Task_Hierarchy) where the value is fixed to 3.
12102          --  See comments in System.Tasking.Initialization.Init_RTS for the
12103          --  value 3.
12104
12105          if Restriction_Active (No_Task_Hierarchy) = False then
12106             Append_To (Args, Make_Identifier (Loc, Name_uMaster));
12107          else
12108             Append_To (Args, Make_Integer_Literal (Loc, 3));
12109          end if;
12110       end if;
12111
12112       --  State parameter. This is a pointer to the task body procedure. The
12113       --  required value is obtained by taking 'Unrestricted_Access of the task
12114       --  body procedure and converting it (with an unchecked conversion) to
12115       --  the type required by the task kernel. For further details, see the
12116       --  description of Expand_N_Task_Body. We use 'Unrestricted_Access rather
12117       --  than 'Address in order to avoid creating trampolines.
12118
12119       declare
12120          Body_Proc    : constant Node_Id := Get_Task_Body_Procedure (Ttyp);
12121          Subp_Ptr_Typ : constant Node_Id :=
12122                           Create_Itype (E_Access_Subprogram_Type, Tdec);
12123          Ref          : constant Node_Id := Make_Itype_Reference (Loc);
12124
12125       begin
12126          Set_Directly_Designated_Type (Subp_Ptr_Typ, Body_Proc);
12127          Set_Etype (Subp_Ptr_Typ, Subp_Ptr_Typ);
12128
12129          --  Be sure to freeze a reference to the access-to-subprogram type,
12130          --  otherwise gigi will complain that it's in the wrong scope, because
12131          --  it's actually inside the init procedure for the record type that
12132          --  corresponds to the task type.
12133
12134          --  This processing is causing a crash in the .NET/JVM back ends that
12135          --  is not yet understood, so skip it in these cases ???
12136
12137          if VM_Target = No_VM then
12138             Set_Itype (Ref, Subp_Ptr_Typ);
12139             Append_Freeze_Action (Task_Rec, Ref);
12140
12141             Append_To (Args,
12142               Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
12143                 Make_Qualified_Expression (Loc,
12144                   Subtype_Mark => New_Reference_To (Subp_Ptr_Typ, Loc),
12145                   Expression   =>
12146                     Make_Attribute_Reference (Loc,
12147                       Prefix =>
12148                         New_Occurrence_Of (Body_Proc, Loc),
12149                       Attribute_Name => Name_Unrestricted_Access))));
12150
12151          --  For the .NET/JVM cases revert to the original code below ???
12152
12153          else
12154             Append_To (Args,
12155               Unchecked_Convert_To (RTE (RE_Task_Procedure_Access),
12156                 Make_Attribute_Reference (Loc,
12157                   Prefix =>
12158                     New_Occurrence_Of (Body_Proc, Loc),
12159                   Attribute_Name => Name_Address)));
12160          end if;
12161       end;
12162
12163       --  Discriminants parameter. This is just the address of the task
12164       --  value record itself (which contains the discriminant values
12165
12166       Append_To (Args,
12167         Make_Attribute_Reference (Loc,
12168           Prefix => Make_Identifier (Loc, Name_uInit),
12169           Attribute_Name => Name_Address));
12170
12171       --  Elaborated parameter. This is an access to the elaboration Boolean
12172
12173       Append_To (Args,
12174         Make_Attribute_Reference (Loc,
12175           Prefix => Make_Identifier (Loc, New_External_Name (Tnam, 'E')),
12176           Attribute_Name => Name_Unchecked_Access));
12177
12178       --  Chain parameter. This is a reference to the _Chain parameter of
12179       --  the initialization procedure.
12180
12181       Append_To (Args, Make_Identifier (Loc, Name_uChain));
12182
12183       --  Task name parameter. Take this from the _Task_Id parameter to the
12184       --  init call unless there is a Task_Name pragma, in which case we take
12185       --  the value from the pragma.
12186
12187       if Present (Tdef)
12188         and then Has_Task_Name_Pragma (Tdef)
12189       then
12190          --  Copy expression in full, because it may be dynamic and have
12191          --  side effects.
12192
12193          Append_To (Args,
12194            New_Copy_Tree
12195              (Expression (First
12196                            (Pragma_Argument_Associations
12197                              (Find_Task_Or_Protected_Pragma
12198                                (Tdef, Name_Task_Name))))));
12199
12200       else
12201          Append_To (Args, Make_Identifier (Loc, Name_uTask_Name));
12202       end if;
12203
12204       --  Created_Task parameter. This is the _Task_Id field of the task
12205       --  record value
12206
12207       Append_To (Args,
12208         Make_Selected_Component (Loc,
12209           Prefix => Make_Identifier (Loc, Name_uInit),
12210           Selector_Name => Make_Identifier (Loc, Name_uTask_Id)));
12211
12212       --  Build_Entry_Names generation flag. When set to true, the runtime
12213       --  will allocate an array to hold the string names of task entries.
12214
12215       if not Restricted_Profile then
12216          if Has_Entries (Ttyp)
12217            and then Entry_Names_OK
12218          then
12219             Append_To (Args, New_Reference_To (Standard_True, Loc));
12220          else
12221             Append_To (Args, New_Reference_To (Standard_False, Loc));
12222          end if;
12223       end if;
12224
12225       if Restricted_Profile then
12226          Name := New_Reference_To (RTE (RE_Create_Restricted_Task), Loc);
12227       else
12228          Name := New_Reference_To (RTE (RE_Create_Task), Loc);
12229       end if;
12230
12231       return
12232         Make_Procedure_Call_Statement (Loc,
12233           Name => Name,
12234           Parameter_Associations => Args);
12235    end Make_Task_Create_Call;
12236
12237    ------------------------------
12238    -- Next_Protected_Operation --
12239    ------------------------------
12240
12241    function Next_Protected_Operation (N : Node_Id) return Node_Id is
12242       Next_Op : Node_Id;
12243
12244    begin
12245       Next_Op := Next (N);
12246       while Present (Next_Op)
12247         and then not Nkind_In (Next_Op, N_Subprogram_Body, N_Entry_Body)
12248       loop
12249          Next (Next_Op);
12250       end loop;
12251
12252       return Next_Op;
12253    end Next_Protected_Operation;
12254
12255    ---------------------
12256    -- Null_Statements --
12257    ---------------------
12258
12259    function Null_Statements (Stats : List_Id) return Boolean is
12260       Stmt : Node_Id;
12261
12262    begin
12263       Stmt := First (Stats);
12264       while Nkind (Stmt) /= N_Empty
12265         and then (Nkind_In (Stmt, N_Null_Statement, N_Label)
12266                     or else
12267                       (Nkind (Stmt) = N_Pragma
12268                          and then (Pragma_Name (Stmt) = Name_Unreferenced
12269                                      or else
12270                                    Pragma_Name (Stmt) = Name_Unmodified
12271                                      or else
12272                                    Pragma_Name (Stmt) = Name_Warnings)))
12273       loop
12274          Next (Stmt);
12275       end loop;
12276
12277       return Nkind (Stmt) = N_Empty;
12278    end Null_Statements;
12279
12280    --------------------------
12281    -- Parameter_Block_Pack --
12282    --------------------------
12283
12284    function Parameter_Block_Pack
12285      (Loc     : Source_Ptr;
12286       Blk_Typ : Entity_Id;
12287       Actuals : List_Id;
12288       Formals : List_Id;
12289       Decls   : List_Id;
12290       Stmts   : List_Id) return Node_Id
12291    is
12292       Actual    : Entity_Id;
12293       Expr      : Node_Id := Empty;
12294       Formal    : Entity_Id;
12295       Has_Param : Boolean := False;
12296       P         : Entity_Id;
12297       Params    : List_Id;
12298       Temp_Asn  : Node_Id;
12299       Temp_Nam  : Node_Id;
12300
12301    begin
12302       Actual := First (Actuals);
12303       Formal := Defining_Identifier (First (Formals));
12304       Params := New_List;
12305
12306       while Present (Actual) loop
12307          if Is_By_Copy_Type (Etype (Actual)) then
12308             --  Generate:
12309             --    Jnn : aliased <formal-type>
12310
12311             Temp_Nam :=
12312               Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
12313
12314             Append_To (Decls,
12315               Make_Object_Declaration (Loc,
12316                 Aliased_Present =>
12317                   True,
12318                 Defining_Identifier =>
12319                   Temp_Nam,
12320                 Object_Definition =>
12321                   New_Reference_To (Etype (Formal), Loc)));
12322
12323             if Ekind (Formal) /= E_Out_Parameter then
12324
12325                --  Generate:
12326                --    Jnn := <actual>
12327
12328                Temp_Asn :=
12329                  New_Reference_To (Temp_Nam, Loc);
12330
12331                Set_Assignment_OK (Temp_Asn);
12332
12333                Append_To (Stmts,
12334                  Make_Assignment_Statement (Loc,
12335                    Name =>
12336                      Temp_Asn,
12337                    Expression =>
12338                      New_Copy_Tree (Actual)));
12339             end if;
12340
12341             --  Generate:
12342             --    Jnn'unchecked_access
12343
12344             Append_To (Params,
12345               Make_Attribute_Reference (Loc,
12346                 Attribute_Name =>
12347                   Name_Unchecked_Access,
12348                 Prefix =>
12349                   New_Reference_To (Temp_Nam, Loc)));
12350
12351             Has_Param := True;
12352
12353          --  The controlling parameter is omitted
12354
12355          else
12356             if not Is_Controlling_Actual (Actual) then
12357                Append_To (Params,
12358                  Make_Reference (Loc, New_Copy_Tree (Actual)));
12359
12360                Has_Param := True;
12361             end if;
12362          end if;
12363
12364          Next_Actual (Actual);
12365          Next_Formal_With_Extras (Formal);
12366       end loop;
12367
12368       if Has_Param then
12369          Expr := Make_Aggregate (Loc, Params);
12370       end if;
12371
12372       --  Generate:
12373       --    P : Ann := (
12374       --      J1'unchecked_access;
12375       --      <actual2>'reference;
12376       --      ...);
12377
12378       P := Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
12379
12380       Append_To (Decls,
12381         Make_Object_Declaration (Loc,
12382           Defining_Identifier =>
12383             P,
12384           Object_Definition =>
12385             New_Reference_To (Blk_Typ, Loc),
12386           Expression =>
12387             Expr));
12388
12389       return P;
12390    end Parameter_Block_Pack;
12391
12392    ----------------------------
12393    -- Parameter_Block_Unpack --
12394    ----------------------------
12395
12396    function Parameter_Block_Unpack
12397      (Loc     : Source_Ptr;
12398       P       : Entity_Id;
12399       Actuals : List_Id;
12400       Formals : List_Id) return List_Id
12401    is
12402       Actual    : Entity_Id;
12403       Asnmt     : Node_Id;
12404       Formal    : Entity_Id;
12405       Has_Asnmt : Boolean := False;
12406       Result    : constant List_Id := New_List;
12407
12408    begin
12409       Actual := First (Actuals);
12410       Formal := Defining_Identifier (First (Formals));
12411       while Present (Actual) loop
12412          if Is_By_Copy_Type (Etype (Actual))
12413            and then Ekind (Formal) /= E_In_Parameter
12414          then
12415             --  Generate:
12416             --    <actual> := P.<formal>;
12417
12418             Asnmt :=
12419               Make_Assignment_Statement (Loc,
12420                 Name =>
12421                   New_Copy (Actual),
12422                 Expression =>
12423                   Make_Explicit_Dereference (Loc,
12424                     Make_Selected_Component (Loc,
12425                       Prefix =>
12426                         New_Reference_To (P, Loc),
12427                       Selector_Name =>
12428                         Make_Identifier (Loc, Chars (Formal)))));
12429
12430             Set_Assignment_OK (Name (Asnmt));
12431             Append_To (Result, Asnmt);
12432
12433             Has_Asnmt := True;
12434          end if;
12435
12436          Next_Actual (Actual);
12437          Next_Formal_With_Extras (Formal);
12438       end loop;
12439
12440       if Has_Asnmt then
12441          return Result;
12442       else
12443          return New_List (Make_Null_Statement (Loc));
12444       end if;
12445    end Parameter_Block_Unpack;
12446
12447    ----------------------
12448    -- Set_Discriminals --
12449    ----------------------
12450
12451    procedure Set_Discriminals (Dec : Node_Id) is
12452       D       : Entity_Id;
12453       Pdef    : Entity_Id;
12454       D_Minal : Entity_Id;
12455
12456    begin
12457       pragma Assert (Nkind (Dec) = N_Protected_Type_Declaration);
12458       Pdef := Defining_Identifier (Dec);
12459
12460       if Has_Discriminants (Pdef) then
12461          D := First_Discriminant (Pdef);
12462          while Present (D) loop
12463             D_Minal :=
12464               Make_Defining_Identifier (Sloc (D),
12465                 Chars => New_External_Name (Chars (D), 'D'));
12466
12467             Set_Ekind (D_Minal, E_Constant);
12468             Set_Etype (D_Minal, Etype (D));
12469             Set_Scope (D_Minal, Pdef);
12470             Set_Discriminal (D, D_Minal);
12471             Set_Discriminal_Link (D_Minal, D);
12472
12473             Next_Discriminant (D);
12474          end loop;
12475       end if;
12476    end Set_Discriminals;
12477
12478    -----------------------
12479    -- Trivial_Accept_OK --
12480    -----------------------
12481
12482    function Trivial_Accept_OK return Boolean is
12483    begin
12484       case Opt.Task_Dispatching_Policy is
12485
12486          --  If we have the default task dispatching policy in effect, we can
12487          --  definitely do the optimization (one way of looking at this is to
12488          --  think of the formal definition of the default policy being allowed
12489          --  to run any task it likes after a rendezvous, so even if notionally
12490          --  a full rescheduling occurs, we can say that our dispatching policy
12491          --  (i.e. the default dispatching policy) reorders the queue to be the
12492          --  same as just before the call.
12493
12494          when ' ' =>
12495             return True;
12496
12497          --  FIFO_Within_Priorities certainly does not permit this
12498          --  optimization since the Rendezvous is a scheduling action that may
12499          --  require some other task to be run.
12500
12501          when 'F' =>
12502             return False;
12503
12504          --  For now, disallow the optimization for all other policies. This
12505          --  may be over-conservative, but it is certainly not incorrect.
12506
12507          when others =>
12508             return False;
12509
12510       end case;
12511    end Trivial_Accept_OK;
12512
12513 end Exp_Ch9;