OSDN Git Service

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