OSDN Git Service

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