exp_unst.adb 101 KB
Newer Older
1 2 3 4 5 6 7 8
------------------------------------------------------------------------------
--                                                                          --
--                         GNAT COMPILER COMPONENTS                         --
--                                                                          --
--                             E X P _ U N S T                              --
--                                                                          --
--                                 B o d y                                  --
--                                                                          --
9
--          Copyright (C) 2014-2019, Free Software Foundation, Inc.         --
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
--                                                                          --
-- GNAT is free software;  you can  redistribute it  and/or modify it under --
-- terms of the  GNU General Public License as published  by the Free Soft- --
-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
-- for  more details.  You should have  received  a copy of the GNU General --
-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license.          --
--                                                                          --
-- GNAT was originally developed  by the GNAT team at  New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc.      --
--                                                                          --
------------------------------------------------------------------------------

with Atree;    use Atree;
Arnaud Charlet committed
27
with Debug;    use Debug;
28 29
with Einfo;    use Einfo;
with Elists;   use Elists;
30
with Exp_Util; use Exp_Util;
31
with Lib;      use Lib;
32 33 34
with Namet;    use Namet;
with Nlists;   use Nlists;
with Nmake;    use Nmake;
35
with Opt;
Arnaud Charlet committed
36
with Output;   use Output;
37
with Rtsfind;  use Rtsfind;
38
with Sem;      use Sem;
Arnaud Charlet committed
39
with Sem_Aux;  use Sem_Aux;
40
with Sem_Ch8;  use Sem_Ch8;
41 42
with Sem_Mech; use Sem_Mech;
with Sem_Res;  use Sem_Res;
43 44
with Sem_Util; use Sem_Util;
with Sinfo;    use Sinfo;
Arnaud Charlet committed
45
with Sinput;   use Sinput;
46
with Snames;   use Snames;
47
with Stand;    use Stand;
48
with Tbuild;   use Tbuild;
Arnaud Charlet committed
49
with Uintp;    use Uintp;
50 51 52

package body Exp_Unst is

53 54 55 56
   -----------------------
   -- Local Subprograms --
   -----------------------

57 58
   procedure Unnest_Subprogram
     (Subp : Entity_Id; Subp_Body : Node_Id; For_Inline : Boolean := False);
59 60 61 62 63
   --  Subp is a library-level subprogram which has nested subprograms, and
   --  Subp_Body is the corresponding N_Subprogram_Body node. This procedure
   --  declares the AREC types and objects, adds assignments to the AREC record
   --  as required, defines the xxxPTR types for uplevel referenced objects,
   --  adds the ARECP parameter to all nested subprograms which need it, and
64 65 66 67
   --  modifies all uplevel references appropriately. If For_Inline is True,
   --  we're unnesting this subprogram because it's on the list of inlined
   --  subprograms and should unnest it despite it not being part of the main
   --  unit.
68

Arnaud Charlet committed
69 70 71 72 73
   -----------
   -- Calls --
   -----------

   --  Table to record calls within the nest being analyzed. These are the
Arnaud Charlet committed
74 75 76
   --  calls which may need to have an AREC actual added. This table is built
   --  new for each subprogram nest and cleared at the end of processing each
   --  subprogram nest.
Arnaud Charlet committed
77

Arnaud Charlet committed
78
   type Call_Entry is record
79
      N : Node_Id;
Arnaud Charlet committed
80 81
      --  The actual call

Arnaud Charlet committed
82 83
      Caller : Entity_Id;
      --  Entity of the subprogram containing the call (can be at any level)
Arnaud Charlet committed
84

Arnaud Charlet committed
85 86 87 88
      Callee : Entity_Id;
      --  Entity of the subprogram called (always at level 2 or higher). Note
      --  that in accordance with the basic rules of nesting, the level of To
      --  is either less than or equal to the level of From, or one greater.
Arnaud Charlet committed
89 90 91 92 93 94 95 96
   end record;

   package Calls is new Table.Table (
     Table_Component_Type => Call_Entry,
     Table_Index_Type     => Nat,
     Table_Low_Bound      => 1,
     Table_Initial        => 100,
     Table_Increment      => 200,
97
     Table_Name           => "Unnest_Calls");
Arnaud Charlet committed
98 99 100 101
   --  Records each call within the outer subprogram and all nested subprograms
   --  that are to other subprograms nested within the outer subprogram. These
   --  are the calls that may need an additional parameter.

Arnaud Charlet committed
102 103 104 105
   procedure Append_Unique_Call (Call : Call_Entry);
   --  Append a call entry to the Calls table. A check is made to see if the
   --  table already contains this entry and if so it has no effect.

106
   ----------------------------------
107
   -- Subprograms For Fat Pointers --
108 109 110 111 112 113 114 115 116 117
   ----------------------------------

   function Build_Access_Type_Decl
     (E    : Entity_Id;
      Scop : Entity_Id) return Node_Id;
   --  For an uplevel reference that involves an unconstrained array type,
   --  build an access type declaration for the corresponding activation
   --  record component. The relevant attributes of the access type are
   --  set here to avoid a full analysis that would require a scope stack.

118 119 120 121 122
   function Needs_Fat_Pointer (E : Entity_Id) return Boolean;
   --  A formal parameter of an unconstrained array type that appears in an
   --  uplevel reference requires the construction of an access type, to be
   --  used in the corresponding component declaration.

Arnaud Charlet committed
123 124 125
   -----------
   -- Urefs --
   -----------
126

Arnaud Charlet committed
127 128 129 130
   --  Table to record explicit uplevel references to objects (variables,
   --  constants, formal parameters). These are the references that will
   --  need rewriting to use the activation table (AREC) pointers. Also
   --  included are implicit and explicit uplevel references to types, but
Arnaud Charlet committed
131 132 133
   --  these do not get rewritten by the front end. This table is built new
   --  for each subprogram nest and cleared at the end of processing each
   --  subprogram nest.
134

Arnaud Charlet committed
135 136 137 138 139 140
   type Uref_Entry is record
      Ref : Node_Id;
      --  The reference itself. For objects this is always an entity reference
      --  and the referenced entity will have its Is_Uplevel_Referenced_Entity
      --  flag set and will appear in the Uplevel_Referenced_Entities list of
      --  the subprogram declaring this entity.
141

Arnaud Charlet committed
142 143
      Ent : Entity_Id;
      --  The Entity_Id of the uplevel referenced object or type
Arnaud Charlet committed
144

Arnaud Charlet committed
145 146
      Caller : Entity_Id;
      --  The entity for the subprogram immediately containing this entity
Arnaud Charlet committed
147

Arnaud Charlet committed
148 149 150
      Callee : Entity_Id;
      --  The entity for the subprogram containing the referenced entity. Note
      --  that the level of Callee must be less than the level of Caller, since
Arnaud Charlet committed
151
      --  this is an uplevel reference.
Arnaud Charlet committed
152
   end record;
153

Arnaud Charlet committed
154 155 156 157 158 159 160
   package Urefs is new Table.Table (
     Table_Component_Type => Uref_Entry,
     Table_Index_Type     => Nat,
     Table_Low_Bound      => 1,
     Table_Initial        => 100,
     Table_Increment      => 200,
     Table_Name           => "Unnest_Urefs");
161

Arnaud Charlet committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
   ------------------------
   -- Append_Unique_Call --
   ------------------------

   procedure Append_Unique_Call (Call : Call_Entry) is
   begin
      for J in Calls.First .. Calls.Last loop
         if Calls.Table (J) = Call then
            return;
         end if;
      end loop;

      Calls.Append (Call);
   end Append_Unique_Call;

177 178 179 180 181 182 183 184
   -----------------------------
   --  Build_Access_Type_Decl --
   -----------------------------

   function Build_Access_Type_Decl
     (E    : Entity_Id;
      Scop : Entity_Id) return Node_Id
   is
185 186
      Loc : constant Source_Ptr := Sloc (E);
      Typ : Entity_Id;
187 188 189 190 191 192 193 194

   begin
      Typ := Make_Temporary (Loc, 'S');
      Set_Ekind (Typ, E_General_Access_Type);
      Set_Etype (Typ, Typ);
      Set_Scope (Typ, Scop);
      Set_Directly_Designated_Type (Typ, Etype (E));

195 196 197 198 199 200
      return
        Make_Full_Type_Declaration (Loc,
          Defining_Identifier => Typ,
          Type_Definition     =>
            Make_Access_To_Object_Definition (Loc,
              Subtype_Indication => New_Occurrence_Of (Etype (E), Loc)));
201 202
   end Build_Access_Type_Decl;

Arnaud Charlet committed
203 204 205 206 207 208 209
   ---------------
   -- Get_Level --
   ---------------

   function Get_Level (Subp : Entity_Id; Sub : Entity_Id) return Nat is
      Lev : Nat;
      S   : Entity_Id;
210

Arnaud Charlet committed
211 212 213 214 215 216 217 218
   begin
      Lev := 1;
      S   := Sub;
      loop
         if S = Subp then
            return Lev;
         else
            Lev := Lev + 1;
219
            S   := Enclosing_Subprogram (S);
Arnaud Charlet committed
220 221 222 223
         end if;
      end loop;
   end Get_Level;

224 225 226 227 228 229 230 231 232 233 234
   --------------------------
   -- In_Synchronized_Unit --
   --------------------------

   function In_Synchronized_Unit (Subp : Entity_Id) return Boolean is
      S : Entity_Id := Scope (Subp);

   begin
      while Present (S) and then S /= Standard_Standard loop
         if Is_Concurrent_Type (S) then
            return True;
235 236 237 238 239 240

         elsif Is_Private_Type (S)
           and then Present (Full_View (S))
           and then Is_Concurrent_Type (Full_View (S))
         then
            return True;
241 242 243 244 245 246 247 248
         end if;

         S := Scope (S);
      end loop;

      return False;
   end In_Synchronized_Unit;

249 250 251 252 253
   -----------------------
   -- Needs_Fat_Pointer --
   -----------------------

   function Needs_Fat_Pointer (E : Entity_Id) return Boolean is
254
      Typ : Entity_Id;
255
   begin
256 257 258 259 260 261
      if Is_Formal (E) then
         Typ := Etype (E);
         if Is_Private_Type (Typ) and then Present (Full_View (Typ)) then
            Typ := Full_View (Typ);
         end if;

262
         return Is_Array_Type (Typ) and then not Is_Constrained (Typ);
263 264 265
      else
         return False;
      end if;
266 267
   end Needs_Fat_Pointer;

Arnaud Charlet committed
268 269 270 271 272
   ----------------
   -- Subp_Index --
   ----------------

   function Subp_Index (Sub : Entity_Id) return SI_Type is
Arnaud Charlet committed
273 274
      E : Entity_Id := Sub;

Arnaud Charlet committed
275
   begin
Arnaud Charlet committed
276 277 278 279 280
      pragma Assert (Is_Subprogram (E));

      if Subps_Index (E) = Uint_0 then
         E := Ultimate_Alias (E);

281
         --  The body of a protected operation has a different name and
282 283
         --  has been scanned at this point, and thus has an entry in the
         --  subprogram table.
284

285
         if E = Sub and then Convention (E) = Convention_Protected then
286 287 288
            E := Protected_Body_Subprogram (E);
         end if;

Arnaud Charlet committed
289 290 291 292 293 294 295 296 297 298
         if Ekind (E) = E_Function
           and then Rewritten_For_C (E)
           and then Present (Corresponding_Procedure (E))
         then
            E := Corresponding_Procedure (E);
         end if;
      end if;

      pragma Assert (Subps_Index (E) /= Uint_0);
      return SI_Type (UI_To_Int (Subps_Index (E)));
Arnaud Charlet committed
299 300
   end Subp_Index;

301 302 303 304
   -----------------------
   -- Unnest_Subprogram --
   -----------------------

305 306
   procedure Unnest_Subprogram
     (Subp : Entity_Id; Subp_Body : Node_Id; For_Inline : Boolean := False) is
Arnaud Charlet committed
307 308
      function AREC_Name (J : Pos; S : String) return Name_Id;
      --  Returns name for string ARECjS, where j is the decimal value of j
309

310
      function Enclosing_Subp (Subp : SI_Type) return SI_Type;
Arnaud Charlet committed
311 312 313 314
      --  Subp is the index of a subprogram which has a Lev greater than 1.
      --  This function returns the index of the enclosing subprogram which
      --  will have a Lev value one less than this.

Arnaud Charlet committed
315 316 317 318 319 320 321
      function Img_Pos (N : Pos) return String;
      --  Return image of N without leading blank

      function Upref_Name
        (Ent   : Entity_Id;
         Index : Pos;
         Clist : List_Id) return Name_Id;
Arnaud Charlet committed
322
      --  This function returns the name to be used in the activation record to
Arnaud Charlet committed
323
      --  reference the variable uplevel. Clist is the list of components that
Arnaud Charlet committed
324 325 326 327 328
      --  have been created in the activation record so far. Normally the name
      --  is just a copy of the Chars field of the entity. The exception is
      --  when the name has already been used, in which case we suffix the name
      --  with the index value Index to avoid duplication. This happens with
      --  declare blocks and generic parameters at least.
Arnaud Charlet committed
329

Arnaud Charlet committed
330 331 332
      ---------------
      -- AREC_Name --
      ---------------
333

Arnaud Charlet committed
334
      function AREC_Name (J : Pos; S : String) return Name_Id is
335
      begin
Arnaud Charlet committed
336
         return Name_Find ("AREC" & Img_Pos (J) & S);
Arnaud Charlet committed
337
      end AREC_Name;
338

339 340 341
      --------------------
      -- Enclosing_Subp --
      --------------------
Arnaud Charlet committed
342

343
      function Enclosing_Subp (Subp : SI_Type) return SI_Type is
Arnaud Charlet committed
344
         STJ : Subp_Entry renames Subps.Table (Subp);
345
         Ret : constant SI_Type := Subp_Index (Enclosing_Subprogram (STJ.Ent));
Arnaud Charlet committed
346 347 348 349
      begin
         pragma Assert (STJ.Lev > 1);
         pragma Assert (Subps.Table (Ret).Lev = STJ.Lev - 1);
         return Ret;
350
      end Enclosing_Subp;
Arnaud Charlet committed
351

Arnaud Charlet committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
      -------------
      -- Img_Pos --
      -------------

      function Img_Pos (N : Pos) return String is
         Buf : String (1 .. 20);
         Ptr : Natural;
         NV  : Nat;

      begin
         Ptr := Buf'Last;
         NV := N;
         while NV /= 0 loop
            Buf (Ptr) := Character'Val (48 + NV mod 10);
            Ptr := Ptr - 1;
            NV := NV / 10;
         end loop;

         return Buf (Ptr + 1 .. Buf'Last);
      end Img_Pos;

Arnaud Charlet committed
373
      ----------------
Arnaud Charlet committed
374 375 376
      -- Upref_Name --
      ----------------

Arnaud Charlet committed
377 378 379 380 381
      function Upref_Name
        (Ent   : Entity_Id;
         Index : Pos;
         Clist : List_Id) return Name_Id
      is
Arnaud Charlet committed
382
         C : Node_Id;
Arnaud Charlet committed
383
      begin
Arnaud Charlet committed
384 385 386 387
         C := First (Clist);
         loop
            if No (C) then
               return Chars (Ent);
Arnaud Charlet committed
388

Arnaud Charlet committed
389
            elsif Chars (Defining_Identifier (C)) = Chars (Ent) then
Arnaud Charlet committed
390 391
               return
                 Name_Find (Get_Name_String (Chars (Ent)) & Img_Pos (Index));
Arnaud Charlet committed
392 393 394 395
            else
               Next (C);
            end if;
         end loop;
Arnaud Charlet committed
396 397
      end Upref_Name;

398 399 400
   --  Start of processing for Unnest_Subprogram

   begin
Arnaud Charlet committed
401 402 403 404 405
      --  Nothing to do inside a generic (all processing is for instance)

      if Inside_A_Generic then
         return;
      end if;
Arnaud Charlet committed
406

407 408 409 410
      --  If the main unit is a package body then we need to examine the spec
      --  to determine whether the main unit is generic (the scope stack is not
      --  present when this is called on the main unit).

411 412
      if not For_Inline
        and then Ekind (Cunit_Entity (Main_Unit)) = E_Package_Body
413 414 415 416
        and then Is_Generic_Unit (Spec_Entity (Cunit_Entity (Main_Unit)))
      then
         return;

417 418 419 420
      --  Only unnest when generating code for the main source unit or if
      --  we're unnesting for inline.  But in some Annex E cases the Sloc
      --  points to a different unit, so also make sure that the Parent
      --  isn't in something that we know we're generating code for.
421

422 423
      elsif not For_Inline
        and then not In_Extended_Main_Code_Unit (Subp_Body)
424
        and then not In_Extended_Main_Code_Unit (Parent (Subp_Body))
425
      then
426 427 428
         return;
      end if;

Arnaud Charlet committed
429 430 431 432 433 434
      --  This routine is called late, after the scope stack is gone. The
      --  following creates a suitable dummy scope stack to be used for the
      --  analyze/expand calls made from this routine.

      Push_Scope (Subp);

435 436
      --  First step, we must mark all nested subprograms that require a static
      --  link (activation record) because either they contain explicit uplevel
Arnaud Charlet committed
437 438 439
      --  references (as indicated by Is_Uplevel_Referenced_Entity being set at
      --  this point), or they make calls to other subprograms in the same nest
      --  that require a static link (in which case we set this flag).
440 441 442 443 444 445 446

      --  This is a recursive definition, and to implement this, we have to
      --  build a call graph for the set of nested subprograms, and then go
      --  over this graph to implement recursively the invariant that if a
      --  subprogram has a call to a subprogram requiring a static link, then
      --  the calling subprogram requires a static link.

Arnaud Charlet committed
447
      --  First populate the above tables
448

Arnaud Charlet committed
449
      Subps_First := Subps.Last + 1;
450
      Calls.Init;
Arnaud Charlet committed
451
      Urefs.Init;
452 453

      Build_Tables : declare
454
         Current_Subprogram : Entity_Id := Empty;
Arnaud Charlet committed
455 456 457
         --  When we scan a subprogram body, we set Current_Subprogram to the
         --  corresponding entity. This gets recursively saved and restored.

458 459 460
         function Visit_Node (N : Node_Id) return Traverse_Result;
         --  Visit a single node in Subp

Arnaud Charlet committed
461 462 463 464 465 466 467
         -----------
         -- Visit --
         -----------

         procedure Visit is new Traverse_Proc (Visit_Node);
         --  Used to traverse the body of Subp, populating the tables

468 469 470 471 472
         ----------------
         -- Visit_Node --
         ----------------

         function Visit_Node (N : Node_Id) return Traverse_Result is
Arnaud Charlet committed
473 474 475 476
            Ent    : Entity_Id;
            Caller : Entity_Id;
            Callee : Entity_Id;

477
            procedure Check_Static_Type
478 479 480
              (T                : Entity_Id;
               N                : Node_Id;
               DT               : in out Boolean;
481
               Check_Designated : Boolean := False);
Arnaud Charlet committed
482 483 484 485 486
            --  Given a type T, checks if it is a static type defined as a type
            --  with no dynamic bounds in sight. If so, the only action is to
            --  set Is_Static_Type True for T. If T is not a static type, then
            --  all types with dynamic bounds associated with T are detected,
            --  and their bounds are marked as uplevel referenced if not at the
487 488 489
            --  library level, and DT is set True. If N is specified, it's the
            --  node that will need to be replaced. If not specified, it means
            --  we can't do a replacement because the bound is implicit.
Arnaud Charlet committed
490

491 492 493
            --  If Check_Designated is True and T or its full view is an access
            --  type, check whether the designated type has dynamic bounds.

Arnaud Charlet committed
494 495
            procedure Note_Uplevel_Ref
              (E      : Entity_Id;
496
               N      : Node_Id;
Arnaud Charlet committed
497 498 499 500 501 502
               Caller : Entity_Id;
               Callee : Entity_Id);
            --  Called when we detect an explicit or implicit uplevel reference
            --  from within Caller to entity E declared in Callee. E can be a
            --  an object or a type.

503 504 505 506
            procedure Register_Subprogram (E : Entity_Id; Bod : Node_Id);
            --  Enter a subprogram whose body is visible or which is a
            --  subprogram instance into the subprogram table.

Arnaud Charlet committed
507 508 509 510
            -----------------------
            -- Check_Static_Type --
            -----------------------

511
            procedure Check_Static_Type
512 513 514
              (T                : Entity_Id;
               N                : Node_Id;
               DT               : in out Boolean;
515
               Check_Designated : Boolean := False)
516 517
            is
               procedure Note_Uplevel_Bound (N : Node_Id; Ref : Node_Id);
Arnaud Charlet committed
518 519 520 521 522
               --  N is the bound of a dynamic type. This procedure notes that
               --  this bound is uplevel referenced, it can handle references
               --  to entities (typically _FIRST and _LAST entities), and also
               --  attribute references of the form T'name (name is typically
               --  FIRST or LAST) where T is the uplevel referenced bound.
523 524
               --  Ref, if Present, is the location of the reference to
               --  replace.
Arnaud Charlet committed
525 526 527 528 529

               ------------------------
               -- Note_Uplevel_Bound --
               ------------------------

530
               procedure Note_Uplevel_Bound (N : Node_Id; Ref : Node_Id) is
Arnaud Charlet committed
531
               begin
532
                  --  Entity name case. Make sure that the entity is declared
533 534
                  --  in a subprogram. This may not be the case for a type in a
                  --  loop appearing in a precondition.
535 536
                  --  Exclude explicitly  discriminants (that can appear
                  --  in bounds of discriminated components).
Arnaud Charlet committed
537 538

                  if Is_Entity_Name (N) then
539
                     if Present (Entity (N))
540
                       and then not Is_Type (Entity (N))
541
                       and then Present (Enclosing_Subprogram (Entity (N)))
542
                       and then Ekind (Entity (N)) /= E_Discriminant
543
                     then
Arnaud Charlet committed
544 545
                        Note_Uplevel_Ref
                          (E      => Entity (N),
546
                           N      => Empty,
Arnaud Charlet committed
547 548 549
                           Caller => Current_Subprogram,
                           Callee => Enclosing_Subprogram (Entity (N)));
                     end if;
550

551 552 553 554 555 556 557
                  --  Attribute or indexed component case

                  elsif Nkind_In (N, N_Attribute_Reference,
                                     N_Indexed_Component)
                  then
                     Note_Uplevel_Bound (Prefix (N), Ref);

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
                     --  The indices of the indexed components, or the
                     --  associated expressions of an attribute reference,
                     --  may also involve uplevel references.

                     declare
                        Expr : Node_Id;

                     begin
                        Expr := First (Expressions (N));
                        while Present (Expr) loop
                           Note_Uplevel_Bound (Expr, Ref);
                           Next (Expr);
                        end loop;
                     end;

573 574 575 576 577 578
                     --  The type of the prefix may be have an uplevel
                     --  reference if this needs bounds.

                     if Nkind (N) = N_Attribute_Reference then
                        declare
                           Attr : constant Attribute_Id :=
579 580 581
                                    Get_Attribute_Id (Attribute_Name (N));
                           DT   : Boolean := False;

582 583 584 585 586 587
                        begin
                           if (Attr = Attribute_First
                                 or else Attr = Attribute_Last
                                 or else Attr = Attribute_Length)
                             and then Is_Constrained (Etype (Prefix (N)))
                           then
588 589
                              Check_Static_Type
                                (Etype (Prefix (N)), Empty, DT);
590 591 592 593
                           end if;
                        end;
                     end if;

594 595
                  --  Binary operator cases. These can apply to arrays for
                  --  which we may need bounds.
596 597 598 599 600 601 602 603 604 605

                  elsif Nkind (N) in N_Binary_Op then
                     Note_Uplevel_Bound (Left_Opnd (N),  Ref);
                     Note_Uplevel_Bound (Right_Opnd (N), Ref);

                  --  Unary operator case

                  elsif Nkind (N) in N_Unary_Op then
                     Note_Uplevel_Bound (Right_Opnd (N), Ref);

606
                  --  Explicit dereference and selected component case
607

608 609
                  elsif Nkind_In (N, N_Explicit_Dereference,
                                     N_Selected_Component)
610
                  then
611 612
                     Note_Uplevel_Bound (Prefix (N), Ref);

613
                  --  Conditional expressions
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639

                  elsif Nkind (N) = N_If_Expression then
                     declare
                        Expr : Node_Id;

                     begin
                        Expr := First (Expressions (N));
                        while Present (Expr) loop
                           Note_Uplevel_Bound (Expr, Ref);
                           Next (Expr);
                        end loop;
                     end;

                  elsif Nkind (N) = N_Case_Expression then
                     declare
                        Alternative : Node_Id;

                     begin
                        Note_Uplevel_Bound (Expression (N), Ref);

                        Alternative := First (Alternatives (N));
                        while Present (Alternative) loop
                           Note_Uplevel_Bound (Expression (Alternative), Ref);
                        end loop;
                     end;

640
                  --  Conversion case
641

642 643
                  elsif Nkind (N) = N_Type_Conversion then
                     Note_Uplevel_Bound (Expression (N), Ref);
Arnaud Charlet committed
644 645
                  end if;
               end Note_Uplevel_Bound;
646

Arnaud Charlet committed
647
            --  Start of processing for Check_Static_Type
648 649

            begin
Arnaud Charlet committed
650
               --  If already marked static, immediate return
651

652
               if Is_Static_Type (T) and then not Check_Designated then
Arnaud Charlet committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
                  return;
               end if;

               --  If the type is at library level, always consider it static,
               --  since such uplevel references are irrelevant.

               if Is_Library_Level_Entity (T) then
                  Set_Is_Static_Type (T);
                  return;
               end if;

               --  Otherwise figure out what the story is with this type

               --  For a scalar type, check bounds

               if Is_Scalar_Type (T) then

                  --  If both bounds static, then this is a static type

                  declare
                     LB : constant Node_Id := Type_Low_Bound (T);
                     UB : constant Node_Id := Type_High_Bound (T);

                  begin
                     if not Is_Static_Expression (LB) then
678
                        Note_Uplevel_Bound (LB, N);
Arnaud Charlet committed
679
                        DT := True;
680
                     end if;
Arnaud Charlet committed
681 682

                     if not Is_Static_Expression (UB) then
683
                        Note_Uplevel_Bound (UB, N);
Arnaud Charlet committed
684 685 686 687
                        DT := True;
                     end if;
                  end;

688 689
               --  For record type, check all components and discriminant
               --  constraints if present.
Arnaud Charlet committed
690 691 692 693

               elsif Is_Record_Type (T) then
                  declare
                     C : Entity_Id;
694 695
                     D : Elmt_Id;

Arnaud Charlet committed
696 697 698
                  begin
                     C := First_Component_Or_Discriminant (T);
                     while Present (C) loop
699
                        Check_Static_Type (Etype (C), N, DT);
Arnaud Charlet committed
700 701
                        Next_Component_Or_Discriminant (C);
                     end loop;
702 703 704 705 706 707 708 709 710 711 712 713 714 715

                     if Has_Discriminants (T)
                       and then Present (Discriminant_Constraint (T))
                     then
                        D := First_Elmt (Discriminant_Constraint (T));
                        while Present (D) loop
                           if not Is_Static_Expression (Node (D)) then
                              Note_Uplevel_Bound (Node (D), N);
                              DT := True;
                           end if;

                           Next_Elmt (D);
                        end loop;
                     end if;
Arnaud Charlet committed
716 717
                  end;

Arnaud Charlet committed
718
               --  For array type, check index types and component type
Arnaud Charlet committed
719 720 721 722 723

               elsif Is_Array_Type (T) then
                  declare
                     IX : Node_Id;
                  begin
724
                     Check_Static_Type (Component_Type (T), N, DT);
Arnaud Charlet committed
725 726 727

                     IX := First_Index (T);
                     while Present (IX) loop
728
                        Check_Static_Type (Etype (IX), N, DT);
Arnaud Charlet committed
729 730 731 732
                        Next_Index (IX);
                     end loop;
                  end;

Arnaud Charlet committed
733 734
               --  For private type, examine whether full view is static

735 736 737 738
               elsif Is_Incomplete_Or_Private_Type (T)
                 and then Present (Full_View (T))
               then
                  Check_Static_Type (Full_View (T), N, DT, Check_Designated);
Arnaud Charlet committed
739 740 741 742 743

                  if Is_Static_Type (Full_View (T)) then
                     Set_Is_Static_Type (T);
                  end if;

744
               --  For access types, check designated type when required
745 746 747 748

               elsif Is_Access_Type (T) and then Check_Designated then
                  Check_Static_Type (Directly_Designated_Type (T), N, DT);

Arnaud Charlet committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
               --  For now, ignore other types

               else
                  return;
               end if;

               if not DT then
                  Set_Is_Static_Type (T);
               end if;
            end Check_Static_Type;

            ----------------------
            -- Note_Uplevel_Ref --
            ----------------------

            procedure Note_Uplevel_Ref
              (E      : Entity_Id;
766
               N      : Node_Id;
Arnaud Charlet committed
767 768 769
               Caller : Entity_Id;
               Callee : Entity_Id)
            is
770
               Full_E : Entity_Id := E;
Arnaud Charlet committed
771 772 773 774 775 776 777 778 779 780 781
            begin
               --  Nothing to do for static type

               if Is_Static_Type (E) then
                  return;
               end if;

               --  Nothing to do if Caller and Callee are the same

               if Caller = Callee then
                  return;
Arnaud Charlet committed
782

Arnaud Charlet committed
783 784 785
               --  Callee may be a function that returns an array, and that has
               --  been rewritten as a procedure. If caller is that procedure,
               --  nothing to do either.
Arnaud Charlet committed
786 787 788

               elsif Ekind (Callee) = E_Function
                 and then Rewritten_For_C (Callee)
Arnaud Charlet committed
789
                 and then Corresponding_Procedure (Callee) = Caller
Arnaud Charlet committed
790 791
               then
                  return;
792 793 794

               elsif Ekind_In (Callee, E_Entry, E_Entry_Family) then
                  return;
Arnaud Charlet committed
795 796 797 798
               end if;

               --  We have a new uplevel referenced entity

799 800 801 802
               if Ekind (E) = E_Constant and then Present (Full_View (E)) then
                  Full_E := Full_View (E);
               end if;

Arnaud Charlet committed
803
               --  All we do at this stage is to add the uplevel reference to
Arnaud Charlet committed
804
               --  the table. It's too early to do anything else, since this
Arnaud Charlet committed
805 806 807
               --  uplevel reference may come from an unreachable subprogram
               --  in which case the entry will be deleted.

808
               Urefs.Append ((N, Full_E, Caller, Callee));
Arnaud Charlet committed
809
            end Note_Uplevel_Ref;
810

811 812 813 814 815 816
            -------------------------
            -- Register_Subprogram --
            -------------------------

            procedure Register_Subprogram (E : Entity_Id; Bod : Node_Id) is
               L : constant Nat := Get_Level (Subp, E);
817

818
            begin
819 820 821
               --  Subprograms declared in tasks and protected types cannot be
               --  eliminated because calls to them may be in other units, so
               --  they must be treated as reachable.
822

823 824 825 826
               Subps.Append
                 ((Ent           => E,
                   Bod           => Bod,
                   Lev           => L,
827 828
                   Reachable     => In_Synchronized_Unit (E)
                                      or else Address_Taken (E),
829 830 831 832 833 834 835 836 837 838
                   Uplevel_Ref   => L,
                   Declares_AREC => False,
                   Uents         => No_Elist,
                   Last          => 0,
                   ARECnF        => Empty,
                   ARECn         => Empty,
                   ARECnT        => Empty,
                   ARECnPT       => Empty,
                   ARECnP        => Empty,
                   ARECnU        => Empty));
839

840
               Set_Subps_Index (E, UI_From_Int (Subps.Last));
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856

               --  If we marked this reachable because it's in a synchronized
               --  unit, we have to mark all enclosing subprograms as reachable
               --  as well.

               if In_Synchronized_Unit (E) then
                  declare
                     S : Entity_Id := E;

                  begin
                     for J in reverse 1 .. L  - 1 loop
                        S := Enclosing_Subprogram (S);
                        Subps.Table (Subp_Index (S)).Reachable := True;
                     end loop;
                  end;
               end if;
857 858
            end Register_Subprogram;

859 860 861
         --  Start of processing for Visit_Node

         begin
862
            case Nkind (N) is
Arnaud Charlet committed
863

864
               --  Record a subprogram call
865

866 867 868
               when N_Function_Call
                  | N_Procedure_Call_Statement
               =>
869
                  --  We are only interested in direct calls, not indirect
870 871
                  --  calls (where Name (N) is an explicit dereference) at
                  --  least for now!
872

873 874
                  if Nkind (Name (N)) in N_Has_Entity then
                     Ent := Entity (Name (N));
875

876 877 878
                     --  We are only interested in calls to subprograms nested
                     --  within Subp. Calls to Subp itself or to subprograms
                     --  outside the nested structure do not affect us.
879

880 881 882 883 884 885 886
                     if Scope_Within (Ent, Subp)
                        and then Is_Subprogram (Ent)
                        and then not Is_Imported (Ent)
                     then
                        Append_Unique_Call ((N, Current_Subprogram, Ent));
                     end if;
                  end if;
Arnaud Charlet committed
887

888 889 890
                  --  For all calls where the formal is an unconstrained array
                  --  and the actual is constrained we need to check the bounds
                  --  for uplevel references.
Arnaud Charlet committed
891

892 893 894
                  declare
                     Actual : Entity_Id;
                     DT     : Boolean := False;
895 896
                     Formal : Node_Id;
                     Subp   : Entity_Id;
897

898 899 900
                  begin
                     if Nkind (Name (N)) = N_Explicit_Dereference then
                        Subp := Etype (Name (N));
901
                     else
902 903
                        Subp := Entity (Name (N));
                     end if;
904

905 906 907 908 909 910 911 912
                     Actual := First_Actual (N);
                     Formal := First_Formal_With_Extras (Subp);
                     while Present (Actual) loop
                        if Is_Array_Type (Etype (Formal))
                          and then not Is_Constrained (Etype (Formal))
                          and then Is_Constrained (Etype (Actual))
                        then
                           Check_Static_Type (Etype (Actual), Empty, DT);
913
                        end if;
914

915 916 917 918
                        Next_Actual (Actual);
                        Next_Formal_With_Extras (Formal);
                     end loop;
                  end;
919

920 921 922 923
               --  An At_End_Proc in a statement sequence indicates that there
               --  is a call from the enclosing construct or block to that
               --  subprogram. As above, the called entity must be local and
               --  not imported.
924

925 926 927 928 929
               when N_Handled_Sequence_Of_Statements =>
                  if Present (At_End_Proc (N))
                    and then Scope_Within (Entity (At_End_Proc (N)), Subp)
                    and then not Is_Imported (Entity (At_End_Proc (N)))
                  then
930 931
                     Append_Unique_Call
                       ((N, Current_Subprogram, Entity (At_End_Proc (N))));
932 933
                  end if;

934 935
               --  Similarly, the following constructs include a semantic
               --  attribute Procedure_To_Call that must be handled like
936
               --  other calls. Likewise for attribute Storage_Pool.
937 938 939

               when N_Allocator
                  | N_Extended_Return_Statement
940
                  | N_Free_Statement
941 942 943
                  | N_Simple_Return_Statement
               =>
                  declare
944
                     Pool : constant Entity_Id := Storage_Pool (N);
945
                     Proc : constant Entity_Id := Procedure_To_Call (N);
946

947 948 949 950 951 952 953
                  begin
                     if Present (Proc)
                       and then Scope_Within (Proc, Subp)
                       and then not Is_Imported (Proc)
                     then
                        Append_Unique_Call ((N, Current_Subprogram, Proc));
                     end if;
954 955 956 957 958 959 960 961 962 963 964 965

                     if Present (Pool)
                       and then not Is_Library_Level_Entity (Pool)
                       and then Scope_Within_Or_Same (Scope (Pool), Subp)
                     then
                        Caller := Current_Subprogram;
                        Callee := Enclosing_Subprogram (Pool);

                        if Callee /= Caller then
                           Note_Uplevel_Ref (Pool, Empty, Caller, Callee);
                        end if;
                     end if;
966 967
                  end;

968 969 970
                  --  For an allocator with a qualified expression, check type
                  --  of expression being qualified. The explicit type name is
                  --  handled as an entity reference.
971 972

                  if Nkind (N) = N_Allocator
973
                    and then Nkind (Expression (N)) = N_Qualified_Expression
974 975 976 977 978 979 980
                  then
                     declare
                        DT : Boolean := False;
                     begin
                        Check_Static_Type
                          (Etype (Expression (Expression (N))), Empty,  DT);
                     end;
981 982 983 984 985 986 987 988 989 990 991 992

                  --  For a Return or Free (all other nodes we handle here),
                  --  we usually need the size of the object, so we need to be
                  --  sure that any nonstatic bounds of the expression's type
                  --  that are uplevel are handled.

                  elsif Nkind (N) /= N_Allocator
                    and then Present (Expression (N))
                  then
                     declare
                        DT : Boolean := False;
                     begin
993 994 995 996 997
                        Check_Static_Type
                          (Etype (Expression (N)),
                           Empty,
                           DT,
                           Check_Designated => Nkind (N) = N_Free_Statement);
998
                     end;
999 1000
                  end if;

1001 1002
               --  A 'Access reference is a (potential) call. So is 'Address,
               --  in particular on imported subprograms. Other attributes
1003
               --  require special handling.
1004

1005 1006 1007 1008 1009 1010 1011 1012 1013
               when N_Attribute_Reference =>
                  declare
                     Attr : constant Attribute_Id :=
                              Get_Attribute_Id (Attribute_Name (N));
                  begin
                     case Attr is
                        when Attribute_Access
                           | Attribute_Unchecked_Access
                           | Attribute_Unrestricted_Access
1014
                           | Attribute_Address
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                        =>
                           if Nkind (Prefix (N)) in N_Has_Entity then
                              Ent := Entity (Prefix (N));

                              --  We only need to examine calls to subprograms
                              --  nested within current Subp.

                              if Scope_Within (Ent, Subp) then
                                 if Is_Imported (Ent) then
                                    null;

                                 elsif Is_Subprogram (Ent) then
                                    Append_Unique_Call
                                      ((N, Current_Subprogram, Ent));
                                 end if;
                              end if;
                           end if;
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
                        --  References to bounds can be uplevel references if
                        --  the type isn't static.

                        when Attribute_First
                           | Attribute_Last
                           | Attribute_Length
                        =>
                           --  Special-case attributes of objects whose bounds
                           --  may be uplevel references. More complex prefixes
                           --  handled during full traversal. Note that if the
                           --  nominal subtype of the prefix is unconstrained,
                           --  the bound must be obtained from the object, not
                           --  from the (possibly) uplevel reference.

                           if Is_Constrained (Etype (Prefix (N))) then
                              declare
                                 DT : Boolean := False;
                              begin
1051 1052
                                 Check_Static_Type
                                   (Etype (Prefix (N)), Empty, DT);
1053 1054 1055 1056
                              end;

                              return OK;
                           end if;
1057

1058 1059 1060 1061
                        when others =>
                           null;
                     end case;
                  end;
1062

1063 1064 1065
               --  Component associations in aggregates are either static or
               --  else the aggregate will be expanded into assignments, in
               --  which case the expression is analyzed later and provides
1066 1067 1068
               --  no relevant code generation.

               when N_Component_Association =>
1069 1070 1071
                  if No (Expression (N))
                    or else No (Etype (Expression (N)))
                  then
1072 1073 1074
                     return Skip;
                  end if;

1075
               --  Generic associations are not analyzed: the actuals are
1076
               --  transferred to renaming and subtype declarations that
1077 1078 1079 1080 1081
               --  are the ones that must be examined.

               when N_Generic_Association =>
                  return Skip;

1082 1083 1084
               --  Indexed references can be uplevel if the type isn't static
               --  and if the lower bound (or an inner bound for a multi-
               --  dimensional array) is uplevel.
1085

1086 1087 1088
               when N_Indexed_Component
                  | N_Slice
               =>
1089 1090 1091 1092 1093 1094 1095
                  if Is_Constrained (Etype (Prefix (N))) then
                     declare
                        DT : Boolean := False;
                     begin
                        Check_Static_Type (Etype (Prefix (N)), Empty, DT);
                     end;
                  end if;
1096

1097 1098 1099 1100
                  --  A selected component can have an implicit up-level
                  --  reference due to the bounds of previous fields in the
                  --  record. We simplify the processing here by examining
                  --  all components of the record.
1101

1102 1103 1104
                  --  Selected components appear as unit names and end labels
                  --  for child units. Prefixes of these nodes denote parent
                  --  units and carry no type information so they are skipped.
1105

1106 1107 1108 1109 1110 1111 1112 1113
               when N_Selected_Component =>
                  if Present (Etype (Prefix (N))) then
                     declare
                        DT : Boolean := False;
                     begin
                        Check_Static_Type (Etype (Prefix (N)), Empty, DT);
                     end;
                  end if;
1114

1115 1116 1117 1118
               --  For EQ/NE comparisons, we need the type of the operands
               --  in order to do the comparison, which means we need the
               --  bounds.

1119 1120 1121
               when N_Op_Eq
                  | N_Op_Ne
               =>
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
                  declare
                     DT : Boolean := False;
                  begin
                     Check_Static_Type (Etype (Left_Opnd  (N)), Empty, DT);
                     Check_Static_Type (Etype (Right_Opnd (N)), Empty, DT);
                  end;

               --  Likewise we need the sizes to compute how much to move in
               --  an assignment.

               when N_Assignment_Statement =>
                  declare
                     DT : Boolean := False;
                  begin
                     Check_Static_Type (Etype (Name       (N)), Empty, DT);
                     Check_Static_Type (Etype (Expression (N)), Empty, DT);
                  end;

1140 1141 1142 1143 1144
               --  Record a subprogram. We record a subprogram body that acts
               --  as a spec. Otherwise we record a subprogram declaration,
               --  providing that it has a corresponding body we can get hold
               --  of. The case of no corresponding body being available is
               --  ignored for now.
1145

1146 1147
               when N_Subprogram_Body =>
                  Ent := Unique_Defining_Entity (N);
1148

1149
                  --  Ignore generic subprogram
1150

1151 1152 1153
                  if Is_Generic_Subprogram (Ent) then
                     return Skip;
                  end if;
1154

1155
                  --  Make new entry in subprogram table if not already made
1156

1157
                  Register_Subprogram (Ent, N);
1158

1159 1160
                  --  We make a recursive call to scan the subprogram body, so
                  --  that we can save and restore Current_Subprogram.
1161

1162 1163 1164
                  declare
                     Save_CS : constant Entity_Id := Current_Subprogram;
                     Decl    : Node_Id;
Arnaud Charlet committed
1165

1166 1167
                  begin
                     Current_Subprogram := Ent;
Arnaud Charlet committed
1168

1169
                     --  Scan declarations
Arnaud Charlet committed
1170

1171 1172 1173 1174 1175
                     Decl := First (Declarations (N));
                     while Present (Decl) loop
                        Visit (Decl);
                        Next (Decl);
                     end loop;
Arnaud Charlet committed
1176

1177
                     --  Scan statements
Arnaud Charlet committed
1178

1179
                     Visit (Handled_Statement_Sequence (N));
Arnaud Charlet committed
1180

1181
                     --  Restore current subprogram setting
Arnaud Charlet committed
1182

1183 1184
                     Current_Subprogram := Save_CS;
                  end;
Arnaud Charlet committed
1185

1186 1187
                  --  Now at this level, return skipping the subprogram body
                  --  descendants, since we already took care of them!
Arnaud Charlet committed
1188

1189
                  return Skip;
Arnaud Charlet committed
1190

1191 1192
               --  If we have a body stub, visit the associated subunit, which
               --  is a semantic descendant of the stub.
Arnaud Charlet committed
1193

1194 1195
               when N_Body_Stub =>
                  Visit (Library_Unit (N));
Arnaud Charlet committed
1196

1197 1198 1199
               --  A declaration of a wrapper package indicates a subprogram
               --  instance for which there is no explicit body. Enter the
               --  subprogram instance in the table.
Arnaud Charlet committed
1200

1201 1202 1203 1204 1205
               when N_Package_Declaration =>
                  if Is_Wrapper_Package (Defining_Entity (N)) then
                     Register_Subprogram
                       (Related_Instance (Defining_Entity (N)), Empty);
                  end if;
Arnaud Charlet committed
1206

1207
               --  Skip generic declarations
Arnaud Charlet committed
1208

1209 1210 1211 1212
               when N_Generic_Declaration =>
                  return Skip;

               --  Skip generic package body
Arnaud Charlet committed
1213

1214 1215 1216 1217 1218 1219
               when N_Package_Body =>
                  if Present (Corresponding_Spec (N))
                    and then Ekind (Corresponding_Spec (N)) = E_Generic_Package
                  then
                     return Skip;
                  end if;
Arnaud Charlet committed
1220

1221 1222 1223
               --  Pragmas and component declarations are ignored. Quantified
               --  expressions are expanded into explicit loops and the
               --  original epression must be ignored.
1224

1225 1226
               when N_Component_Declaration
                  | N_Pragma
1227
                  | N_Quantified_Expression
1228
               =>
1229 1230
                  return Skip;

1231 1232 1233 1234 1235 1236 1237 1238 1239
               --  We want to skip the function spec for a generic function
               --  to avoid looking at any generic types that might be in
               --  its formals.

               when N_Function_Specification =>
                  if Is_Generic_Subprogram  (Unique_Defining_Entity (N)) then
                     return Skip;
                  end if;

1240
               --  Otherwise record an uplevel reference in a local identifier
Arnaud Charlet committed
1241

1242
               when others =>
1243 1244
                  if Nkind (N) in N_Has_Entity
                    and then Present (Entity (N))
1245 1246
                  then
                     Ent := Entity (N);
Arnaud Charlet committed
1247

1248
                     --  Only interested in entities declared within our nest
Arnaud Charlet committed
1249

1250 1251
                     if not Is_Library_Level_Entity (Ent)
                       and then Scope_Within_Or_Same (Scope (Ent), Subp)
1252

1253
                        --  Skip entities defined in inlined subprograms
1254

1255 1256
                       and then
                         Chars (Enclosing_Subprogram (Ent)) /= Name_uParent
Arnaud Charlet committed
1257

1258 1259
                        --  Constants and variables are potentially uplevel
                        --  references to global declarations.
Arnaud Charlet committed
1260

1261
                       and then
1262 1263 1264
                         (Ekind_In (Ent, E_Constant,
                                         E_Loop_Parameter,
                                         E_Variable)
Arnaud Charlet committed
1265

1266 1267 1268
                           --  Formals are interesting, but not if being used
                           --  as mere names of parameters for name notation
                           --  calls.
Arnaud Charlet committed
1269

1270 1271 1272 1273 1274
                           or else
                             (Is_Formal (Ent)
                               and then not
                                 (Nkind (Parent (N)) = N_Parameter_Association
                                   and then Selector_Name (Parent (N)) = N))
Arnaud Charlet committed
1275

1276 1277
                           --  Types other than known Is_Static types are
                           --  potentially interesting.
Arnaud Charlet committed
1278

1279 1280
                           or else
                             (Is_Type (Ent) and then not Is_Static_Type (Ent)))
1281 1282 1283
                     then
                        --  Here we have a potentially interesting uplevel
                        --  reference to examine.
Arnaud Charlet committed
1284

1285 1286 1287
                        if Is_Type (Ent) then
                           declare
                              DT : Boolean := False;
Arnaud Charlet committed
1288

1289 1290
                           begin
                              Check_Static_Type (Ent, N, DT);
1291
                              return OK;
1292
                           end;
Arnaud Charlet committed
1293 1294
                        end if;

1295 1296
                        Caller := Current_Subprogram;
                        Callee := Enclosing_Subprogram (Ent);
Arnaud Charlet committed
1297

1298
                        if Callee /= Caller
1299 1300
                          and then (not Is_Static_Type (Ent)
                                     or else Needs_Fat_Pointer (Ent))
1301 1302
                        then
                           Note_Uplevel_Ref (Ent, N, Caller, Callee);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

                        --  Check the type of a formal parameter of the current
                        --  subprogram, whose formal type may be an uplevel
                        --  reference.

                        elsif Is_Formal (Ent)
                          and then Scope (Ent) = Current_Subprogram
                        then
                           declare
                              DT : Boolean := False;

                           begin
                              Check_Static_Type (Etype (Ent), Empty, DT);
                           end;
1317 1318
                        end if;
                     end if;
Arnaud Charlet committed
1319
                  end if;
1320
            end case;
1321

Arnaud Charlet committed
1322 1323
            --  Fall through to continue scanning children of this node

1324 1325 1326
            return OK;
         end Visit_Node;

1327 1328
      --  Start of processing for Build_Tables

1329
      begin
Arnaud Charlet committed
1330
         --  Traverse the body to get subprograms, calls and uplevel references
1331

1332 1333 1334
         Visit (Subp_Body);
      end Build_Tables;

Arnaud Charlet committed
1335 1336
      --  Now do the first transitive closure which determines which
      --  subprograms in the nest are actually reachable.
1337

Arnaud Charlet committed
1338
      Reachable_Closure : declare
1339 1340 1341
         Modified : Boolean;

      begin
Arnaud Charlet committed
1342
         Subps.Table (Subps_First).Reachable := True;
Arnaud Charlet committed
1343

1344 1345 1346 1347 1348 1349
         --  We use a simple minded algorithm as follows (obviously this can
         --  be done more efficiently, using one of the standard algorithms
         --  for efficient transitive closure computation, but this is simple
         --  and most likely fast enough that its speed does not matter).

         --  Repeatedly scan the list of calls. Any time we find a call from
Arnaud Charlet committed
1350 1351 1352
         --  A to B, where A is reachable, but B is not, then B is reachable,
         --  and note that we have made a change by setting Modified True. We
         --  repeat this until we make a pass with no modifications.
1353 1354 1355 1356

         Outer : loop
            Modified := False;
            Inner : for J in Calls.First .. Calls.Last loop
Arnaud Charlet committed
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
               declare
                  CTJ : Call_Entry renames Calls.Table (J);

                  SINF : constant SI_Type := Subp_Index (CTJ.Caller);
                  SINT : constant SI_Type := Subp_Index (CTJ.Callee);

                  SUBF : Subp_Entry renames Subps.Table (SINF);
                  SUBT : Subp_Entry renames Subps.Table (SINT);

               begin
                  if SUBF.Reachable and then not SUBT.Reachable then
                     SUBT.Reachable := True;
                     Modified := True;
                  end if;
               end;
1372 1373 1374 1375
            end loop Inner;

            exit Outer when not Modified;
         end loop Outer;
Arnaud Charlet committed
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
      end Reachable_Closure;

      --  Remove calls from unreachable subprograms

      declare
         New_Index : Nat;

      begin
         New_Index := 0;
         for J in Calls.First .. Calls.Last loop
            declare
               CTJ : Call_Entry renames Calls.Table (J);

               SINF : constant SI_Type := Subp_Index (CTJ.Caller);
               SINT : constant SI_Type := Subp_Index (CTJ.Callee);

               SUBF : Subp_Entry renames Subps.Table (SINF);
               SUBT : Subp_Entry renames Subps.Table (SINT);

            begin
               if SUBF.Reachable then
                  pragma Assert (SUBT.Reachable);
                  New_Index := New_Index + 1;
                  Calls.Table (New_Index) := Calls.Table (J);
               end if;
            end;
         end loop;

         Calls.Set_Last (New_Index);
      end;

      --  Remove uplevel references from unreachable subprograms

      declare
         New_Index : Nat;

      begin
         New_Index := 0;
         for J in Urefs.First .. Urefs.Last loop
            declare
               URJ : Uref_Entry renames Urefs.Table (J);

               SINF : constant SI_Type := Subp_Index (URJ.Caller);
               SINT : constant SI_Type := Subp_Index (URJ.Callee);

               SUBF : Subp_Entry renames Subps.Table (SINF);
               SUBT : Subp_Entry renames Subps.Table (SINT);

               S : Entity_Id;

            begin
               --  Keep reachable reference

               if SUBF.Reachable then
                  New_Index := New_Index + 1;
                  Urefs.Table (New_Index) := Urefs.Table (J);

                  --  And since we know we are keeping this one, this is a good
                  --  place to fill in information for a good reference.

                  --  Mark all enclosing subprograms need to declare AREC

                  S := URJ.Caller;
                  loop
                     S := Enclosing_Subprogram (S);
Arnaud Charlet committed
1441

1442
                     --  If we are at the top level, as can happen with
Arnaud Charlet committed
1443
                     --  references to formals in aspects of nested subprogram
1444 1445
                     --  declarations, there are no further subprograms to mark
                     --  as requiring activation records.
Arnaud Charlet committed
1446 1447

                     exit when No (S);
1448 1449 1450 1451 1452 1453 1454 1455

                     declare
                        SUBI : Subp_Entry renames Subps.Table (Subp_Index (S));
                     begin
                        SUBI.Declares_AREC := True;

                        --  If this entity was marked reachable because it is
                        --  in a task or protected type, there may not appear
1456 1457 1458 1459
                        --  to be any calls to it, which would normally adjust
                        --  the levels of the parent subprograms. So we need to
                        --  be sure that the uplevel reference of that entity
                        --  takes into account possible calls.
1460 1461 1462 1463 1464 1465 1466 1467

                        if In_Synchronized_Unit (SUBF.Ent)
                          and then SUBT.Lev < SUBI.Uplevel_Ref
                        then
                           SUBI.Uplevel_Ref := SUBT.Lev;
                        end if;
                     end;

Arnaud Charlet committed
1468 1469 1470 1471 1472 1473 1474
                     exit when S = URJ.Callee;
                  end loop;

                  --  Add to list of uplevel referenced entities for Callee.
                  --  We do not add types to this list, only actual references
                  --  to objects that will be referenced uplevel, and we use
                  --  the flag Is_Uplevel_Referenced_Entity to avoid making
1475 1476 1477
                  --  duplicate entries in the list. Discriminants are also
                  --  excluded, only the enclosing object can appear in the
                  --  list.
Arnaud Charlet committed
1478

1479 1480 1481
                  if not Is_Uplevel_Referenced_Entity (URJ.Ent)
                    and then Ekind (URJ.Ent) /= E_Discriminant
                  then
Arnaud Charlet committed
1482
                     Set_Is_Uplevel_Referenced_Entity (URJ.Ent);
1483
                     Append_New_Elmt (URJ.Ent, SUBT.Uents);
Arnaud Charlet committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
                  end if;

                  --  And set uplevel indication for caller

                  if SUBT.Lev < SUBF.Uplevel_Ref then
                     SUBF.Uplevel_Ref := SUBT.Lev;
                  end if;
               end if;
            end;
         end loop;

         Urefs.Set_Last (New_Index);
      end;

      --  Remove unreachable subprograms from Subps table. Note that we do
      --  this after eliminating entries from the other two tables, since
Arnaud Charlet committed
1500
      --  those elimination steps depend on referencing the Subps table.
Arnaud Charlet committed
1501 1502 1503 1504 1505

      declare
         New_SI : SI_Type;

      begin
Arnaud Charlet committed
1506
         New_SI := Subps_First - 1;
Arnaud Charlet committed
1507
         for J in Subps_First .. Subps.Last loop
Arnaud Charlet committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
            declare
               STJ  : Subp_Entry renames Subps.Table (J);
               Spec : Node_Id;
               Decl : Node_Id;

            begin
               --  Subprogram is reachable, copy and reset index

               if STJ.Reachable then
                  New_SI := New_SI + 1;
                  Subps.Table (New_SI) := STJ;
                  Set_Subps_Index (STJ.Ent, UI_From_Int (New_SI));

               --  Subprogram is not reachable

               else
                  --  Clear index, since no longer active

                  Set_Subps_Index (Subps.Table (J).Ent, Uint_0);

                  --  Output debug information if -gnatd.3 set

                  if Debug_Flag_Dot_3 then
                     Write_Str ("Eliminate ");
                     Write_Name (Chars (Subps.Table (J).Ent));
                     Write_Str (" at ");
                     Write_Location (Sloc (Subps.Table (J).Ent));
                     Write_Str (" (not referenced)");
                     Write_Eol;
                  end if;

1539 1540
                  --  Rewrite declaration, body, and corresponding freeze node
                  --  to null statements.
Arnaud Charlet committed
1541

1542 1543 1544
                  --  A subprogram instantiation does not have an explicit
                  --  body. If unused, we could remove the corresponding
                  --  wrapper package and its body (TBD).
Arnaud Charlet committed
1545

1546 1547
                  if Present (STJ.Bod) then
                     Spec := Corresponding_Spec (STJ.Bod);
Arnaud Charlet committed
1548

1549 1550 1551
                     if Present (Spec) then
                        Decl := Parent (Declaration_Node (Spec));
                        Rewrite (Decl, Make_Null_Statement (Sloc (Decl)));
1552 1553 1554 1555 1556

                        if Present (Freeze_Node (Spec)) then
                           Rewrite (Freeze_Node (Spec),
                                    Make_Null_Statement (Sloc (Decl)));
                        end if;
1557 1558 1559 1560
                     end if;

                     Rewrite (STJ.Bod, Make_Null_Statement (Sloc (STJ.Bod)));
                  end if;
Arnaud Charlet committed
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
               end if;
            end;
         end loop;

         Subps.Set_Last (New_SI);
      end;

      --  Now it is time for the second transitive closure, which follows calls
      --  and makes sure that A calls B, and B has uplevel references, then A
      --  is also marked as having uplevel references.

      Closure_Uplevel : declare
         Modified : Boolean;

      begin
         --  We use a simple minded algorithm as follows (obviously this can
         --  be done more efficiently, using one of the standard algorithms
         --  for efficient transitive closure computation, but this is simple
         --  and most likely fast enough that its speed does not matter).

         --  Repeatedly scan the list of calls. Any time we find a call from
         --  A to B, where B has uplevel references, make sure that A is marked
         --  as having at least the same level of uplevel referencing.

         Outer2 : loop
            Modified := False;
            Inner2 : for J in Calls.First .. Calls.Last loop
               declare
                  CTJ  : Call_Entry renames Calls.Table (J);
                  SINF : constant SI_Type := Subp_Index (CTJ.Caller);
                  SINT : constant SI_Type := Subp_Index (CTJ.Callee);
                  SUBF : Subp_Entry renames Subps.Table (SINF);
                  SUBT : Subp_Entry renames Subps.Table (SINT);
               begin
                  if SUBT.Lev > SUBT.Uplevel_Ref
                    and then SUBF.Uplevel_Ref > SUBT.Uplevel_Ref
                  then
                     SUBF.Uplevel_Ref := SUBT.Uplevel_Ref;
                     Modified := True;
                  end if;
               end;
            end loop Inner2;

            exit Outer2 when not Modified;
         end loop Outer2;
      end Closure_Uplevel;

      --  We have one more step before the tables are complete. An uplevel
      --  call from subprogram A to subprogram B where subprogram B has uplevel
      --  references is in effect an uplevel reference, and must arrange for
      --  the proper activation link to be passed.

      for J in Calls.First .. Calls.Last loop
         declare
            CTJ : Call_Entry renames Calls.Table (J);

            SINF : constant SI_Type := Subp_Index (CTJ.Caller);
            SINT : constant SI_Type := Subp_Index (CTJ.Callee);

            SUBF : Subp_Entry renames Subps.Table (SINF);
            SUBT : Subp_Entry renames Subps.Table (SINT);

            A : Entity_Id;

         begin
            --  If callee has uplevel references

            if SUBT.Uplevel_Ref < SUBT.Lev

              --  And this is an uplevel call

              and then SUBT.Lev < SUBF.Lev
            then
               --  We need to arrange for finding the uplink

               A := CTJ.Caller;
               loop
                  A := Enclosing_Subprogram (A);
                  Subps.Table (Subp_Index (A)).Declares_AREC := True;
                  exit when A = CTJ.Callee;

                  --  In any case exit when we get to the outer level. This
                  --  happens in some odd cases with generics (in particular
                  --  sem_ch3.adb does not compile without this kludge ???).

                  exit when A = Subp;
               end loop;
            end if;
         end;
      end loop;
1651

Arnaud Charlet committed
1652 1653 1654 1655 1656
      --  The tables are now complete, so we can record the last index in the
      --  Subps table for later reference in Cprint.

      Subps.Table (Subps_First).Last := Subps.Last;

Arnaud Charlet committed
1657 1658 1659 1660
      --  Next step, create the entities for code we will insert. We do this
      --  at the start so that all the entities are defined, regardless of the
      --  order in which we do the code insertions.

Arnaud Charlet committed
1661
      Create_Entities : for J in Subps_First .. Subps.Last loop
Arnaud Charlet committed
1662 1663 1664
         declare
            STJ : Subp_Entry renames Subps.Table (J);
            Loc : constant Source_Ptr := Sloc (STJ.Bod);
1665

Arnaud Charlet committed
1666
         begin
Arnaud Charlet committed
1667 1668 1669 1670
            --  First we create the ARECnF entity for the additional formal for
            --  all subprograms which need an activation record passed.

            if STJ.Uplevel_Ref < STJ.Lev then
Arnaud Charlet committed
1671
               STJ.ARECnF :=
Arnaud Charlet committed
1672
                 Make_Defining_Identifier (Loc, Chars => AREC_Name (J, "F"));
Arnaud Charlet committed
1673 1674
            end if;

Arnaud Charlet committed
1675
            --  Define the AREC entities for the activation record if needed
1676

Arnaud Charlet committed
1677
            if STJ.Declares_AREC then
Arnaud Charlet committed
1678
               STJ.ARECn   :=
Arnaud Charlet committed
1679
                 Make_Defining_Identifier (Loc, AREC_Name (J, ""));
Arnaud Charlet committed
1680
               STJ.ARECnT  :=
Arnaud Charlet committed
1681
                 Make_Defining_Identifier (Loc, AREC_Name (J, "T"));
Arnaud Charlet committed
1682
               STJ.ARECnPT :=
Arnaud Charlet committed
1683
                 Make_Defining_Identifier (Loc, AREC_Name (J, "PT"));
Arnaud Charlet committed
1684
               STJ.ARECnP  :=
Arnaud Charlet committed
1685
                 Make_Defining_Identifier (Loc, AREC_Name (J, "P"));
Arnaud Charlet committed
1686

Arnaud Charlet committed
1687
               --  Define uplink component entity if inner nesting case
Arnaud Charlet committed
1688

Arnaud Charlet committed
1689
               if Present (STJ.ARECnF) then
Arnaud Charlet committed
1690 1691
                  STJ.ARECnU :=
                    Make_Defining_Identifier (Loc, AREC_Name (J, "U"));
Arnaud Charlet committed
1692
               end if;
Arnaud Charlet committed
1693 1694
            end if;
         end;
Arnaud Charlet committed
1695
      end loop Create_Entities;
Arnaud Charlet committed
1696 1697 1698 1699

      --  Loop through subprograms

      Subp_Loop : declare
1700
         Addr : Entity_Id := Empty;
1701 1702

      begin
Arnaud Charlet committed
1703
         for J in Subps_First .. Subps.Last loop
1704 1705 1706 1707
            declare
               STJ : Subp_Entry renames Subps.Table (J);

            begin
Arnaud Charlet committed
1708
               --  First add the extra formal if needed. This applies to all
1709 1710
               --  nested subprograms that require an activation record to be
               --  passed, as indicated by ARECnF being defined.
Arnaud Charlet committed
1711

1712
               if Present (STJ.ARECnF) then
1713 1714 1715 1716 1717 1718

                  --  Here we need the extra formal. We do the expansion and
                  --  analysis of this manually, since it is fairly simple,
                  --  and it is not obvious how we can get what we want if we
                  --  try to use the normal Analyze circuit.

Arnaud Charlet committed
1719
                  Add_Extra_Formal : declare
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
                     Encl : constant SI_Type := Enclosing_Subp (J);
                     STJE : Subp_Entry renames Subps.Table (Encl);
                     --  Index and Subp_Entry for enclosing routine

                     Form : constant Entity_Id := STJ.ARECnF;
                     --  The formal to be added. Note that n here is one less
                     --  than the level of the subprogram itself (STJ.Ent).

                     procedure Add_Form_To_Spec (F : Entity_Id; S : Node_Id);
                     --  S is an N_Function/Procedure_Specification node, and F
Arnaud Charlet committed
1730 1731
                     --  is the new entity to add to this subprogramn spec as
                     --  the last Extra_Formal.
1732 1733 1734 1735 1736 1737

                     ----------------------
                     -- Add_Form_To_Spec --
                     ----------------------

                     procedure Add_Form_To_Spec (F : Entity_Id; S : Node_Id) is
Arnaud Charlet committed
1738
                        Sub : constant Entity_Id := Defining_Entity (S);
Arnaud Charlet committed
1739
                        Ent : Entity_Id;
1740 1741

                     begin
Arnaud Charlet committed
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
                        --  Case of at least one Extra_Formal is present, set
                        --  ARECnF as the new last entry in the list.

                        if Present (Extra_Formals (Sub)) then
                           Ent := Extra_Formals (Sub);
                           while Present (Extra_Formal (Ent)) loop
                              Ent := Extra_Formal (Ent);
                           end loop;

                           Set_Extra_Formal (Ent, F);

                        --  No Extra formals present
1754 1755

                        else
Arnaud Charlet committed
1756 1757
                           Set_Extra_Formals (Sub, F);
                           Ent := Last_Formal (Sub);
1758

Arnaud Charlet committed
1759 1760 1761
                           if Present (Ent) then
                              Set_Extra_Formal (Ent, F);
                           end if;
1762 1763 1764
                        end if;
                     end Add_Form_To_Spec;

Arnaud Charlet committed
1765
                  --  Start of processing for Add_Extra_Formal
1766 1767 1768 1769

                  begin
                     --  Decorate the new formal entity

1770 1771 1772 1773 1774 1775 1776 1777
                     Set_Scope                (Form, STJ.Ent);
                     Set_Ekind                (Form, E_In_Parameter);
                     Set_Etype                (Form, STJE.ARECnPT);
                     Set_Mechanism            (Form, By_Copy);
                     Set_Never_Set_In_Source  (Form, True);
                     Set_Analyzed             (Form, True);
                     Set_Comes_From_Source    (Form, False);
                     Set_Is_Activation_Record (Form, True);
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788

                     --  Case of only body present

                     if Acts_As_Spec (STJ.Bod) then
                        Add_Form_To_Spec (Form, Specification (STJ.Bod));

                     --  Case of separate spec

                     else
                        Add_Form_To_Spec (Form, Parent (STJ.Ent));
                     end if;
Arnaud Charlet committed
1789
                  end Add_Extra_Formal;
Arnaud Charlet committed
1790 1791
               end if;

Arnaud Charlet committed
1792 1793 1794
               --  Processing for subprograms that declare an activation record

               if Present (STJ.ARECn) then
1795

Arnaud Charlet committed
1796 1797 1798
                  --  Local declarations for one such subprogram

                  declare
1799 1800 1801 1802 1803
                     Loc : constant Source_Ptr := Sloc (STJ.Bod);

                     Decls : constant List_Id := New_List;
                     --  List of new declarations we create

1804
                     Clist : List_Id;
Arnaud Charlet committed
1805
                     Comp  : Entity_Id;
1806

1807
                     Decl_Assign : Node_Id;
1808
                     --  Assignment to set uplink, Empty if none
1809

1810 1811
                     Decl_ARECnT  : Node_Id;
                     Decl_ARECnPT : Node_Id;
Arnaud Charlet committed
1812
                     Decl_ARECn   : Node_Id;
1813 1814 1815
                     Decl_ARECnP  : Node_Id;
                     --  Declaration nodes for the AREC entities we build

1816
                  begin
1817 1818
                     --  Build list of component declarations for ARECnT and
                     --  load System.Address.
1819 1820 1821

                     Clist := Empty_List;

1822 1823 1824 1825
                     if No (Addr) then
                        Addr := RTE (RE_Address);
                     end if;

1826
                     --  If we are in a subprogram that has a static link that
Arnaud Charlet committed
1827
                     --  is passed in (as indicated by ARECnF being defined),
Arnaud Charlet committed
1828 1829 1830
                     --  then include ARECnU : ARECmPT where ARECmPT comes from
                     --  the level one higher than the current level, and the
                     --  entity ARECnPT comes from the enclosing subprogram.
1831

1832
                     if Present (STJ.ARECnF) then
Arnaud Charlet committed
1833 1834
                        declare
                           STJE : Subp_Entry
1835
                                    renames Subps.Table (Enclosing_Subp (J));
Arnaud Charlet committed
1836 1837 1838 1839 1840 1841 1842
                        begin
                           Append_To (Clist,
                             Make_Component_Declaration (Loc,
                               Defining_Identifier  => STJ.ARECnU,
                               Component_Definition =>
                                 Make_Component_Definition (Loc,
                                   Subtype_Indication =>
Arnaud Charlet committed
1843
                                     New_Occurrence_Of (STJE.ARECnPT, Loc))));
Arnaud Charlet committed
1844
                        end;
1845 1846 1847 1848
                     end if;

                     --  Add components for uplevel referenced entities

Arnaud Charlet committed
1849 1850
                     if Present (STJ.Uents) then
                        declare
1851 1852 1853
                           Elmt     : Elmt_Id;
                           Ptr_Decl : Node_Id;
                           Uent     : Entity_Id;
Arnaud Charlet committed
1854

Arnaud Charlet committed
1855 1856 1857 1858
                           Indx : Nat;
                           --  1's origin of index in list of elements. This is
                           --  used to uniquify names if needed in Upref_Name.

Arnaud Charlet committed
1859 1860
                        begin
                           Elmt := First_Elmt (STJ.Uents);
Arnaud Charlet committed
1861
                           Indx := 0;
Arnaud Charlet committed
1862 1863
                           while Present (Elmt) loop
                              Uent := Node (Elmt);
Arnaud Charlet committed
1864
                              Indx := Indx + 1;
Arnaud Charlet committed
1865 1866 1867

                              Comp :=
                                Make_Defining_Identifier (Loc,
Arnaud Charlet committed
1868
                                  Chars => Upref_Name (Uent, Indx, Clist));
Arnaud Charlet committed
1869 1870 1871 1872

                              Set_Activation_Record_Component
                                (Uent, Comp);

1873 1874 1875
                              if Needs_Fat_Pointer (Uent) then

                                 --  Build corresponding access type
Arnaud Charlet committed
1876

1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
                                 Ptr_Decl :=
                                   Build_Access_Type_Decl
                                     (Etype (Uent), STJ.Ent);
                                 Append_To (Decls, Ptr_Decl);

                                 --  And use its type in the corresponding
                                 --  component.

                                 Append_To (Clist,
                                   Make_Component_Declaration (Loc,
                                     Defining_Identifier  => Comp,
                                     Component_Definition =>
                                       Make_Component_Definition (Loc,
                                         Subtype_Indication =>
                                           New_Occurrence_Of
                                             (Defining_Identifier (Ptr_Decl),
1893
                                              Loc))));
1894 1895 1896 1897 1898 1899 1900 1901 1902
                              else
                                 Append_To (Clist,
                                   Make_Component_Declaration (Loc,
                                     Defining_Identifier  => Comp,
                                     Component_Definition =>
                                       Make_Component_Definition (Loc,
                                         Subtype_Indication =>
                                           New_Occurrence_Of (Addr, Loc))));
                              end if;
Arnaud Charlet committed
1903 1904 1905 1906
                              Next_Elmt (Elmt);
                           end loop;
                        end;
                     end if;
1907 1908

                     --  Now we can insert the AREC declarations into the body
Arnaud Charlet committed
1909 1910 1911
                     --    type ARECnT is record .. end record;
                     --    pragma Suppress_Initialization (ARECnT);

Arnaud Charlet committed
1912 1913
                     --  Note that we need to set the Suppress_Initialization
                     --  flag after Decl_ARECnT has been analyzed.
1914 1915 1916 1917 1918 1919 1920 1921 1922

                     Decl_ARECnT :=
                       Make_Full_Type_Declaration (Loc,
                         Defining_Identifier => STJ.ARECnT,
                         Type_Definition     =>
                           Make_Record_Definition (Loc,
                             Component_List =>
                               Make_Component_List (Loc,
                                 Component_Items => Clist)));
1923
                     Append_To (Decls, Decl_ARECnT);
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934

                     --  type ARECnPT is access all ARECnT;

                     Decl_ARECnPT :=
                       Make_Full_Type_Declaration (Loc,
                         Defining_Identifier => STJ.ARECnPT,
                         Type_Definition     =>
                           Make_Access_To_Object_Definition (Loc,
                             All_Present        => True,
                             Subtype_Indication =>
                               New_Occurrence_Of (STJ.ARECnT, Loc)));
Arnaud Charlet committed
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
                     Append_To (Decls, Decl_ARECnPT);

                     --  ARECn : aliased ARECnT;

                     Decl_ARECn :=
                       Make_Object_Declaration (Loc,
                         Defining_Identifier => STJ.ARECn,
                           Aliased_Present   => True,
                           Object_Definition =>
                             New_Occurrence_Of (STJ.ARECnT, Loc));
                     Append_To (Decls, Decl_ARECn);
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956

                     --  ARECnP : constant ARECnPT := ARECn'Access;

                     Decl_ARECnP :=
                       Make_Object_Declaration (Loc,
                         Defining_Identifier => STJ.ARECnP,
                         Constant_Present    => True,
                         Object_Definition   =>
                           New_Occurrence_Of (STJ.ARECnPT, Loc),
                         Expression          =>
                           Make_Attribute_Reference (Loc,
1957
                             Prefix         =>
1958 1959
                               New_Occurrence_Of (STJ.ARECn, Loc),
                             Attribute_Name => Name_Access));
Arnaud Charlet committed
1960
                     Append_To (Decls, Decl_ARECnP);
1961

Arnaud Charlet committed
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
                     --  If we are in a subprogram that has a static link that
                     --  is passed in (as indicated by ARECnF being defined),
                     --  then generate ARECn.ARECmU := ARECmF where m is
                     --  one less than the current level to set the uplink.

                     if Present (STJ.ARECnF) then
                        Decl_Assign :=
                          Make_Assignment_Statement (Loc,
                            Name       =>
                              Make_Selected_Component (Loc,
                                Prefix        =>
                                  New_Occurrence_Of (STJ.ARECn, Loc),
                                Selector_Name =>
                                  New_Occurrence_Of (STJ.ARECnU, Loc)),
                            Expression =>
                              New_Occurrence_Of (STJ.ARECnF, Loc));
                        Append_To (Decls, Decl_Assign);

                     else
                        Decl_Assign := Empty;
                     end if;

1984 1985 1986 1987 1988
                     if No (Declarations (STJ.Bod)) then
                        Set_Declarations (STJ.Bod, Decls);
                     else
                        Prepend_List_To (Declarations (STJ.Bod), Decls);
                     end if;
1989

1990 1991 1992 1993 1994 1995
                     --  Analyze the newly inserted declarations. Note that we
                     --  do not need to establish the whole scope stack, since
                     --  we have already set all entity fields (so there will
                     --  be no searching of upper scopes to resolve names). But
                     --  we do set the scope of the current subprogram, so that
                     --  newly created entities go in the right entity chain.
1996 1997

                     --  We analyze with all checks suppressed (since we do
Arnaud Charlet committed
1998
                     --  not expect any exceptions).
1999

2000
                     Push_Scope (STJ.Ent);
2001
                     Analyze (Decl_ARECnT,  Suppress => All_Checks);
Arnaud Charlet committed
2002 2003 2004 2005 2006 2007 2008 2009

                     --  Note that we need to call Set_Suppress_Initialization
                     --  after Decl_ARECnT has been analyzed, but before
                     --  analyzing Decl_ARECnP so that the flag is properly
                     --  taking into account.

                     Set_Suppress_Initialization (STJ.ARECnT);

2010
                     Analyze (Decl_ARECnPT, Suppress => All_Checks);
Arnaud Charlet committed
2011
                     Analyze (Decl_ARECn,   Suppress => All_Checks);
2012
                     Analyze (Decl_ARECnP,  Suppress => All_Checks);
Arnaud Charlet committed
2013 2014

                     if Present (Decl_Assign) then
Arnaud Charlet committed
2015
                        Analyze (Decl_Assign, Suppress => All_Checks);
Arnaud Charlet committed
2016 2017
                     end if;

2018
                     Pop_Scope;
Arnaud Charlet committed
2019 2020

                     --  Next step, for each uplevel referenced entity, add
Arnaud Charlet committed
2021
                     --  assignment operations to set the component in the
Arnaud Charlet committed
2022 2023
                     --  activation record.

Arnaud Charlet committed
2024
                     if Present (STJ.Uents) then
Arnaud Charlet committed
2025
                        declare
Arnaud Charlet committed
2026
                           Elmt : Elmt_Id;
Arnaud Charlet committed
2027 2028

                        begin
Arnaud Charlet committed
2029 2030 2031 2032 2033 2034 2035
                           Elmt := First_Elmt (STJ.Uents);
                           while Present (Elmt) loop
                              declare
                                 Ent : constant Entity_Id  := Node (Elmt);
                                 Loc : constant Source_Ptr := Sloc (Ent);
                                 Dec : constant Node_Id    :=
                                         Declaration_Node (Ent);
2036

2037 2038
                                 Asn  : Node_Id;
                                 Attr : Name_Id;
2039
                                 Comp : Entity_Id;
2040
                                 Ins  : Node_Id;
2041
                                 Rhs  : Node_Id;
Arnaud Charlet committed
2042 2043 2044 2045

                              begin
                                 --  For parameters, we insert the assignment
                                 --  right after the declaration of ARECnP.
2046 2047 2048 2049
                                 --  For all other entities, we insert the
                                 --  assignment immediately after the
                                 --  declaration of the entity or after the
                                 --  freeze node if present.
Arnaud Charlet committed
2050 2051 2052 2053 2054 2055 2056 2057

                                 --  Note: we don't need to mark the entity
                                 --  as being aliased, because the address
                                 --  attribute will mark it as Address_Taken,
                                 --  and that is good enough.

                                 if Is_Formal (Ent) then
                                    Ins := Decl_ARECnP;
2058 2059 2060 2061

                                 elsif Has_Delayed_Freeze (Ent) then
                                    Ins := Freeze_Node (Ent);

Arnaud Charlet committed
2062 2063 2064 2065 2066 2067
                                 else
                                    Ins := Dec;
                                 end if;

                                 --  Build and insert the assignment:
                                 --    ARECn.nam := nam'Address
2068 2069 2070 2071 2072 2073 2074
                                 --  or else 'Access for unconstrained array

                                 if Needs_Fat_Pointer (Ent) then
                                    Attr := Name_Access;
                                 else
                                    Attr := Name_Address;
                                 end if;
Arnaud Charlet committed
2075

2076 2077 2078 2079 2080
                                 Rhs :=
                                  Make_Attribute_Reference (Loc,
                                    Prefix         =>
                                      New_Occurrence_Of (Ent, Loc),
                                    Attribute_Name => Attr);
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091

                                 --  If the entity is an unconstrained formal
                                 --  we wrap the attribute reference in an
                                 --  unchecked conversion to the type of the
                                 --  activation record component, to prevent
                                 --  spurious subtype conformance errors within
                                 --  instances.

                                 if Is_Formal (Ent)
                                   and then not Is_Constrained (Etype (Ent))
                                 then
2092
                                    --  Find target component and its type
2093 2094 2095 2096 2097 2098

                                    Comp := First_Component (STJ.ARECnT);
                                    while Chars (Comp) /= Chars (Ent) loop
                                       Comp := Next_Component (Comp);
                                    end loop;

2099 2100
                                    Rhs :=
                                      Unchecked_Convert_To (Etype (Comp), Rhs);
2101 2102
                                 end if;

Arnaud Charlet committed
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
                                 Asn :=
                                   Make_Assignment_Statement (Loc,
                                     Name       =>
                                       Make_Selected_Component (Loc,
                                         Prefix        =>
                                           New_Occurrence_Of (STJ.ARECn, Loc),
                                         Selector_Name =>
                                           New_Occurrence_Of
                                             (Activation_Record_Component
                                                (Ent),
                                              Loc)),
2114
                                     Expression => Rhs);
Arnaud Charlet committed
2115

2116 2117 2118
                                 --  If we have a loop parameter, we have
                                 --  to insert before the first statement
                                 --  of the loop. Ins points to the
2119 2120 2121
                                 --  N_Loop_Parameter_Specification or to
                                 --  an N_Iterator_Specification.

2122 2123 2124
                                 if Nkind_In
                                      (Ins, N_Iterator_Specification,
                                            N_Loop_Parameter_Specification)
2125
                                 then
2126 2127
                                    --  Quantified expression are rewritten as
                                    --  loops during expansion.
2128 2129

                                    if Nkind (Parent (Ins)) =
2130
                                         N_Quantified_Expression
2131 2132 2133 2134 2135 2136
                                    then
                                       null;

                                    else
                                       Ins :=
                                         First
2137 2138
                                           (Statements
                                             (Parent (Parent (Ins))));
2139 2140
                                       Insert_Before (Ins, Asn);
                                    end if;
2141 2142 2143 2144

                                 else
                                    Insert_After (Ins, Asn);
                                 end if;
Arnaud Charlet committed
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161

                                 --  Analyze the assignment statement. We do
                                 --  not need to establish the relevant scope
                                 --  stack entries here, because we have
                                 --  already set the correct entity references,
                                 --  so no name resolution is required, and no
                                 --  new entities are created, so we don't even
                                 --  need to set the current scope.

                                 --  We analyze with all checks suppressed
                                 --  (since we do not expect any exceptions).

                                 Analyze (Asn, Suppress => All_Checks);
                              end;

                              Next_Elmt (Elmt);
                           end loop;
Arnaud Charlet committed
2162
                        end;
Arnaud Charlet committed
2163
                     end if;
2164 2165 2166 2167 2168
                  end;
               end if;
            end;
         end loop;
      end Subp_Loop;
Arnaud Charlet committed
2169

2170 2171 2172 2173
      --  Next step, process uplevel references. This has to be done in a
      --  separate pass, after completing the processing in Sub_Loop because we
      --  need all the AREC declarations generated, inserted, and analyzed so
      --  that the uplevel references can be successfully analyzed.
Arnaud Charlet committed
2174

Arnaud Charlet committed
2175
      Uplev_Refs : for J in Urefs.First .. Urefs.Last loop
2176
         declare
Arnaud Charlet committed
2177
            UPJ : Uref_Entry renames Urefs.Table (J);
Arnaud Charlet committed
2178

2179
         begin
Arnaud Charlet committed
2180 2181
            --  Ignore type references, these are implicit references that do
            --  not need rewriting (e.g. the appearence in a conversion).
2182 2183
            --  Also ignore if no reference was specified or if the rewriting
            --  has already been done (this can happen if the N_Identifier
2184 2185 2186
            --  occurs more than one time in the tree). Also ignore references
            --  when not generating C code (in particular for the case of LLVM,
            --  since GNAT-LLVM will handle the processing for up-level refs).
2187

2188
            if No (UPJ.Ref)
2189 2190
              or else not Is_Entity_Name (UPJ.Ref)
              or else not Present (Entity (UPJ.Ref))
2191
              or else not Opt.Generate_C_Code
2192 2193 2194 2195
            then
               goto Continue;
            end if;

Arnaud Charlet committed
2196
            --  Rewrite one reference
Arnaud Charlet committed
2197

Arnaud Charlet committed
2198 2199 2200
            Rewrite_One_Ref : declare
               Loc : constant Source_Ptr := Sloc (UPJ.Ref);
               --  Source location for the reference
Arnaud Charlet committed
2201

Arnaud Charlet committed
2202 2203
               Typ : constant Entity_Id := Etype (UPJ.Ent);
               --  The type of the referenced entity
Arnaud Charlet committed
2204

2205
               Atyp : Entity_Id;
Arnaud Charlet committed
2206
               --  The actual subtype of the reference
Arnaud Charlet committed
2207

Arnaud Charlet committed
2208 2209
               RS_Caller : constant SI_Type := Subp_Index (UPJ.Caller);
               --  Subp_Index for caller containing reference
Arnaud Charlet committed
2210

Arnaud Charlet committed
2211 2212
               STJR : Subp_Entry renames Subps.Table (RS_Caller);
               --  Subp_Entry for subprogram containing reference
Arnaud Charlet committed
2213

Arnaud Charlet committed
2214 2215
               RS_Callee : constant SI_Type := Subp_Index (UPJ.Callee);
               --  Subp_Index for subprogram containing referenced entity
Arnaud Charlet committed
2216

Arnaud Charlet committed
2217 2218
               STJE : Subp_Entry renames Subps.Table (RS_Callee);
               --  Subp_Entry for subprogram containing referenced entity
Arnaud Charlet committed
2219

Arnaud Charlet committed
2220 2221 2222
               Pfx  : Node_Id;
               Comp : Entity_Id;
               SI   : SI_Type;
Arnaud Charlet committed
2223

Arnaud Charlet committed
2224
            begin
2225 2226 2227 2228 2229 2230
               Atyp := Etype (UPJ.Ref);

               if Ekind (Atyp) /= E_Record_Subtype then
                  Atyp := Get_Actual_Subtype (UPJ.Ref);
               end if;

Arnaud Charlet committed
2231 2232 2233
               --  Ignore if no ARECnF entity for enclosing subprogram which
               --  probably happens as a result of not properly treating
               --  instance bodies. To be examined ???
Arnaud Charlet committed
2234

Arnaud Charlet committed
2235 2236
               --  If this test is omitted, then the compilation of freeze.adb
               --  and inline.adb fail in unnesting mode.
Arnaud Charlet committed
2237

Arnaud Charlet committed
2238 2239 2240
               if No (STJR.ARECnF) then
                  goto Continue;
               end if;
2241

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
               --  If this is a reference to a global constant, use its value
               --  rather than create a reference. It is more efficient and
               --  furthermore indispensable if the context requires a
               --  constant, such as a branch of a case statement.

               if Ekind (UPJ.Ent) = E_Constant
                 and then Is_True_Constant (UPJ.Ent)
                 and then Present (Constant_Value (UPJ.Ent))
                 and then Is_Static_Expression (Constant_Value (UPJ.Ent))
               then
2252
                  Rewrite (UPJ.Ref, New_Copy_Tree (Constant_Value (UPJ.Ent)));
2253 2254 2255
                  goto Continue;
               end if;

Arnaud Charlet committed
2256 2257 2258
               --  Push the current scope, so that the pointer type Tnn, and
               --  any subsidiary entities resulting from the analysis of the
               --  rewritten reference, go in the right entity chain.
2259

Arnaud Charlet committed
2260
               Push_Scope (STJR.Ent);
Arnaud Charlet committed
2261

Arnaud Charlet committed
2262 2263 2264
               --  Now we need to rewrite the reference. We have a reference
               --  from level STJR.Lev to level STJE.Lev. The general form of
               --  the rewritten reference for entity X is:
Arnaud Charlet committed
2265

2266
               --    Typ'Deref (ARECaF.ARECbU.ARECcU.ARECdU....ARECmU.X)
Arnaud Charlet committed
2267

Arnaud Charlet committed
2268 2269
               --  where a,b,c,d .. m =
               --    STJR.Lev - 1,  STJR.Lev - 2, .. STJE.Lev
Arnaud Charlet committed
2270

Arnaud Charlet committed
2271
               pragma Assert (STJR.Lev > STJE.Lev);
Arnaud Charlet committed
2272

Arnaud Charlet committed
2273 2274 2275
               --  Compute the prefix of X. Here are examples to make things
               --  clear (with parens to show groupings, the prefix is
               --  everything except the .X at the end).
Arnaud Charlet committed
2276

Arnaud Charlet committed
2277
               --   level 2 to level 1
Arnaud Charlet committed
2278

Arnaud Charlet committed
2279
               --     AREC1F.X
Arnaud Charlet committed
2280

Arnaud Charlet committed
2281
               --   level 3 to level 1
Arnaud Charlet committed
2282

Arnaud Charlet committed
2283
               --     (AREC2F.AREC1U).X
Arnaud Charlet committed
2284

Arnaud Charlet committed
2285
               --   level 4 to level 1
Arnaud Charlet committed
2286

Arnaud Charlet committed
2287
               --     ((AREC3F.AREC2U).AREC1U).X
Arnaud Charlet committed
2288

Arnaud Charlet committed
2289
               --   level 6 to level 2
2290

Arnaud Charlet committed
2291
               --     (((AREC5F.AREC4U).AREC3U).AREC2U).X
2292

Arnaud Charlet committed
2293 2294 2295 2296 2297 2298
               --  In the above, ARECnF and ARECnU are pointers, so there are
               --  explicit dereferences required for these occurrences.

               Pfx :=
                 Make_Explicit_Dereference (Loc,
                   Prefix => New_Occurrence_Of (STJR.ARECnF, Loc));
Arnaud Charlet committed
2299 2300 2301 2302
               SI := RS_Caller;
               for L in STJE.Lev .. STJR.Lev - 2 loop
                  SI := Enclosing_Subp (SI);
                  Pfx :=
Arnaud Charlet committed
2303 2304 2305 2306 2307 2308
                    Make_Explicit_Dereference (Loc,
                      Prefix =>
                        Make_Selected_Component (Loc,
                          Prefix        => Pfx,
                          Selector_Name =>
                            New_Occurrence_Of (Subps.Table (SI).ARECnU, Loc)));
Arnaud Charlet committed
2309
               end loop;
2310

Arnaud Charlet committed
2311
               --  Get activation record component (must exist)
2312

Arnaud Charlet committed
2313 2314
               Comp := Activation_Record_Component (UPJ.Ent);
               pragma Assert (Present (Comp));
2315

2316 2317 2318
               --  Do the replacement. If the component type is an access type,
               --  this is an uplevel reference for an entity that requires a
               --  fat pointer, so dereference the component.
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339

               if Is_Access_Type (Etype (Comp)) then
                  Rewrite (UPJ.Ref,
                    Make_Explicit_Dereference (Loc,
                      Prefix =>
                        Make_Selected_Component (Loc,
                          Prefix        => Pfx,
                          Selector_Name =>
                            New_Occurrence_Of (Comp, Loc))));

               else
                  Rewrite (UPJ.Ref,
                    Make_Attribute_Reference (Loc,
                      Prefix         => New_Occurrence_Of (Atyp, Loc),
                      Attribute_Name => Name_Deref,
                      Expressions    => New_List (
                        Make_Selected_Component (Loc,
                          Prefix        => Pfx,
                          Selector_Name =>
                            New_Occurrence_Of (Comp, Loc)))));
               end if;
2340

Arnaud Charlet committed
2341 2342 2343 2344 2345 2346
               --  Analyze and resolve the new expression. We do not need to
               --  establish the relevant scope stack entries here, because we
               --  have already set all the correct entity references, so no
               --  name resolution is needed. We have already set the current
               --  scope, so that any new entities created will be in the right
               --  scope.
2347

Arnaud Charlet committed
2348 2349
               --  We analyze with all checks suppressed (since we do not
               --  expect any exceptions)
2350

Arnaud Charlet committed
2351
               Analyze_And_Resolve (UPJ.Ref, Typ, Suppress => All_Checks);
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363

               --  Generate an extra temporary to facilitate the C backend
               --  processing this dereference

               if Opt.Modify_Tree_For_C
                 and then Nkind_In (Parent (UPJ.Ref),
                            N_Type_Conversion,
                            N_Unchecked_Type_Conversion)
               then
                  Force_Evaluation (UPJ.Ref, Mode => Strict);
               end if;

Arnaud Charlet committed
2364 2365
               Pop_Scope;
            end Rewrite_One_Ref;
2366
         end;
Arnaud Charlet committed
2367 2368 2369

      <<Continue>>
         null;
2370
      end loop Uplev_Refs;
Arnaud Charlet committed
2371 2372 2373

      --  Finally, loop through all calls adding extra actual for the
      --  activation record where it is required.
2374

2375 2376 2377
      Adjust_Calls : for J in Calls.First .. Calls.Last loop

         --  Process a single call, we are only interested in a call to a
2378
         --  subprogram that actually needs a pointer to an activation record,
2379 2380 2381
         --  as indicated by the ARECnF entity being set. This excludes the
         --  top level subprogram, and any subprogram not having uplevel refs.

2382
         Adjust_One_Call : declare
2383
            CTJ : Call_Entry renames Calls.Table (J);
Arnaud Charlet committed
2384 2385
            STF : Subp_Entry renames Subps.Table (Subp_Index (CTJ.Caller));
            STT : Subp_Entry renames Subps.Table (Subp_Index (CTJ.Callee));
2386 2387 2388 2389 2390 2391 2392

            Loc : constant Source_Ptr := Sloc (CTJ.N);

            Extra  : Node_Id;
            ExtraP : Node_Id;
            SubX   : SI_Type;
            Act    : Node_Id;
2393 2394

         begin
2395
            if Present (STT.ARECnF)
2396
              and then Nkind (CTJ.N) in N_Subprogram_Call
2397
            then
Arnaud Charlet committed
2398 2399 2400 2401
               --  CTJ.N is a call to a subprogram which may require a pointer
               --  to an activation record. The subprogram containing the call
               --  is CTJ.From and the subprogram being called is CTJ.To, so we
               --  have a call from level STF.Lev to level STT.Lev.
2402

2403
               --  There are three possibilities:
2404

2405 2406
               --  For a call to the same level, we just pass the activation
               --  record passed to the calling subprogram.
2407

2408 2409
               if STF.Lev = STT.Lev then
                  Extra := New_Occurrence_Of (STF.ARECnF, Loc);
2410

Arnaud Charlet committed
2411 2412 2413 2414
               --  For a call that goes down a level, we pass a pointer to the
               --  activation record constructed within the caller (which may
               --  be the outer-level subprogram, but also may be a more deeply
               --  nested caller).
2415

2416 2417
               elsif STT.Lev = STF.Lev + 1 then
                  Extra := New_Occurrence_Of (STF.ARECnP, Loc);
2418

2419 2420 2421
                  --  Otherwise we must have an upcall (STT.Lev < STF.LEV),
                  --  since it is not possible to do a downcall of more than
                  --  one level.
2422

2423 2424 2425
                  --  For a call from level STF.Lev to level STT.Lev, we
                  --  have to find the activation record needed by the
                  --  callee. This is as follows:
2426

2427
                  --    ARECaF.ARECbU.ARECcU....ARECmU
2428

2429 2430
                  --  where a,b,c .. m =
                  --    STF.Lev - 1,  STF.Lev - 2, STF.Lev - 3 .. STT.Lev
2431

2432 2433
               else
                  pragma Assert (STT.Lev < STF.Lev);
2434

2435
                  Extra := New_Occurrence_Of (STF.ARECnF, Loc);
Arnaud Charlet committed
2436
                  SubX  := Subp_Index (CTJ.Caller);
2437
                  for K in reverse STT.Lev .. STF.Lev - 1 loop
Arnaud Charlet committed
2438
                     SubX  := Enclosing_Subp (SubX);
2439 2440 2441 2442 2443 2444 2445 2446
                     Extra :=
                       Make_Selected_Component (Loc,
                         Prefix        => Extra,
                         Selector_Name =>
                           New_Occurrence_Of
                             (Subps.Table (SubX).ARECnU, Loc));
                  end loop;
               end if;
2447

2448 2449
               --  Extra is the additional parameter to be added. Build a
               --  parameter association that we can append to the actuals.
2450

2451 2452 2453 2454 2455
               ExtraP :=
                 Make_Parameter_Association (Loc,
                   Selector_Name             =>
                     New_Occurrence_Of (STT.ARECnF, Loc),
                   Explicit_Actual_Parameter => Extra);
2456

2457 2458 2459
               if No (Parameter_Associations (CTJ.N)) then
                  Set_Parameter_Associations (CTJ.N, Empty_List);
               end if;
2460

2461
               Append (ExtraP, Parameter_Associations (CTJ.N));
2462

Arnaud Charlet committed
2463 2464
               --  We need to deal with the actual parameter chain as well. The
               --  newly added parameter is always the last actual.
2465

2466
               Act := First_Named_Actual (CTJ.N);
2467

2468 2469
               if No (Act) then
                  Set_First_Named_Actual (CTJ.N, Extra);
2470

2471 2472 2473 2474 2475 2476 2477
                  --  If call has been relocated (as with an expression in
                  --  an aggregate), set First_Named pointer in original node
                  --  as well, because that's the parent of the parameter list.

                  Set_First_Named_Actual
                    (Parent (List_Containing (ExtraP)), Extra);

2478
               --  Here we must follow the chain and append the new entry
2479

2480 2481 2482 2483 2484
               else
                  loop
                     declare
                        PAN : Node_Id;
                        NNA : Node_Id;
2485

2486 2487 2488 2489
                     begin
                        PAN := Parent (Act);
                        pragma Assert (Nkind (PAN) = N_Parameter_Association);
                        NNA := Next_Named_Actual (PAN);
2490

2491 2492 2493 2494
                        if No (NNA) then
                           Set_Next_Named_Actual (PAN, Extra);
                           exit;
                        end if;
2495

2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
                        Act := NNA;
                     end;
                  end loop;
               end if;

               --  Analyze and resolve the new actual. We do not need to
               --  establish the relevant scope stack entries here, because
               --  we have already set all the correct entity references, so
               --  no name resolution is needed.

               --  We analyze with all checks suppressed (since we do not
               --  expect any exceptions, and also we temporarily turn off
               --  Unested_Subprogram_Mode to avoid trying to mark uplevel
               --  references (not needed at this stage, and in fact causes
               --  a bit of recursive chaos).

               Opt.Unnest_Subprogram_Mode := False;
               Analyze_And_Resolve
                 (Extra, Etype (STT.ARECnF), Suppress => All_Checks);
               Opt.Unnest_Subprogram_Mode := True;
2516
            end if;
2517
         end Adjust_One_Call;
2518
      end loop Adjust_Calls;
2519 2520 2521 2522

      return;
   end Unnest_Subprogram;

2523 2524 2525 2526 2527 2528 2529 2530 2531
   ------------------------
   -- Unnest_Subprograms --
   ------------------------

   procedure Unnest_Subprograms (N : Node_Id) is
      function Search_Subprograms (N : Node_Id) return Traverse_Result;
      --  Tree visitor that search for outer level procedures with nested
      --  subprograms and invokes Unnest_Subprogram()

2532 2533 2534 2535 2536 2537 2538
      ---------------
      -- Do_Search --
      ---------------

      procedure Do_Search is new Traverse_Proc (Search_Subprograms);
      --  Subtree visitor instantiation

2539 2540 2541 2542 2543 2544
      ------------------------
      -- Search_Subprograms --
      ------------------------

      function Search_Subprograms (N : Node_Id) return Traverse_Result is
      begin
Arnaud Charlet committed
2545
         if Nkind_In (N, N_Subprogram_Body, N_Subprogram_Body_Stub) then
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
            declare
               Spec_Id : constant Entity_Id := Unique_Defining_Entity (N);

            begin
               --  We are only interested in subprograms (not generic
               --  subprograms), that have nested subprograms.

               if Is_Subprogram (Spec_Id)
                 and then Has_Nested_Subprogram (Spec_Id)
                 and then Is_Library_Level_Entity (Spec_Id)
               then
                  Unnest_Subprogram (Spec_Id, N);
               end if;
            end;

2561 2562 2563
         --  The proper body of a stub may contain nested subprograms, and
         --  therefore must be visited explicitly. Nested stubs are examined
         --  recursively in Visit_Node.
2564

2565
         elsif Nkind (N) in N_Body_Stub then
2566
            Do_Search (Library_Unit (N));
2567 2568 2569 2570 2571 2572 2573

         --  Skip generic packages

         elsif Nkind (N) = N_Package_Body
           and then Ekind (Corresponding_Spec (N)) = E_Generic_Package
         then
            return Skip;
2574
         end if;
2575

2576 2577
         return OK;
      end Search_Subprograms;
2578

2579 2580 2581
      Subp      : Entity_Id;
      Subp_Body : Node_Id;

2582 2583 2584
   --  Start of processing for Unnest_Subprograms

   begin
2585
      if not Opt.Unnest_Subprogram_Mode or not Opt.Expander_Active then
2586 2587 2588
         return;
      end if;

2589 2590 2591
      --  A specification will contain bodies if it contains instantiations so
      --  examine package or subprogram declaration of the main unit, when it
      --  is present.
2592 2593

      if Nkind (Unit (N)) = N_Package_Body
2594 2595
        or else (Nkind (Unit (N)) = N_Subprogram_Body
                  and then not Acts_As_Spec (N))
2596 2597 2598 2599
      then
         Do_Search (Library_Unit (N));
      end if;

2600
      Do_Search (N);
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615

      --  Unnest any subprograms passed on the list of inlined subprograms

      Subp := First_Inlined_Subprogram (N);

      while Present (Subp) loop
         Subp_Body := Parent (Declaration_Node (Subp));

         if Nkind (Subp_Body) = N_Subprogram_Declaration
           and then Present (Corresponding_Body (Subp_Body))
         then
            Subp_Body := Parent (Declaration_Node
                                   (Corresponding_Body (Subp_Body)));
         end if;

2616
         Unnest_Subprogram (Subp, Subp_Body, For_Inline => True);
2617 2618
         Next_Inlined_Subprogram (Subp);
      end loop;
2619 2620
   end Unnest_Subprograms;

2621
end Exp_Unst;