OSDN Git Service

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