OSDN Git Service

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