OSDN Git Service

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