OSDN Git Service

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