OSDN Git Service

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